有没有办法在一个更大的切片上取消引用迭代器内部的切片?

问题描述 投票:0回答:1

我正在尝试使用windows()迭代切片Vec切片(windows仅适用于切片),但我需要采取char切片(&[char])并使用常规char。问题是因为char切片指向Vec切片,解除引用不起作用。我该如何解决这个问题?

let a = "12345678910111213141516171819";
let vec1: &str = &a;
println!(
    "{:?}",
    vec1.chars()
        .collect::<Vec<char>>()
        .windows(3)
        .map(|b| b.to_digit(10).product())
);

给了我错误

error[E0599]: no method named `to_digit` found for type `&[char]` in the current scope
 --> src/main.rs:9:24
  |
9 |             .map(|b| b.to_digit(10).product())
  |                        ^^^^^^^^

error: aborting due to previous error

我试图让b转换为常规字符,所以to_digit可以使用它,然后使用product找到整个Windows产品。我没有多尝试product,但这是为了以后。我遇到了一个问题,我不知道如何修复,对我来说如何将切片切片转换为值更重要,然后知道如何专门修复这行代码。

string vector rust slice
1个回答
0
投票

我认为这与你所寻找的一致。我通过将链式操作拆分为多个语句并通过在该窗口中打印window和三个整数的乘积来略微修改了您的示例。

fn main() {
    let a = "12345678910111213141516171819";
    // create a vector of u32 from the str
    // in "real" code you should handle the Result
    // returned by `c.to_digit(10)` rather than
    // just unwrapping
    let nums = a
        .chars()
        .map(|c| c.to_digit(10).unwrap())
        .collect::<Vec<u32>>();
    // iterate over windows of size three
    for window in nums.windows(3) {
        // take the product of the current window
        let product: u32 = window.iter().product();
        println!("{:?}: {}", window, product);
    }
}

并输出:

$ cargo run
[1, 2, 3]: 6
[2, 3, 4]: 24
[3, 4, 5]: 60
[4, 5, 6]: 120
[5, 6, 7]: 210
[6, 7, 8]: 336
[7, 8, 9]: 504
[8, 9, 1]: 72
[9, 1, 0]: 0
[1, 0, 1]: 0
[0, 1, 1]: 0
[1, 1, 1]: 1
[1, 1, 2]: 2
[1, 2, 1]: 2
[2, 1, 3]: 6
[1, 3, 1]: 3
[3, 1, 4]: 12
[1, 4, 1]: 4
[4, 1, 5]: 20
[1, 5, 1]: 5
[5, 1, 6]: 30
[1, 6, 1]: 6
[6, 1, 7]: 42
[1, 7, 1]: 7
[7, 1, 8]: 56
[1, 8, 1]: 8
[8, 1, 9]: 72

正如关于这个问题的评论所提到的,你在这里遇到的一个问题是你没有使用你认为自己的类型。当我遇到这种情况时,我通常会引入故意类型错误来检查错误消息:

let nums: () = a
    .chars()
    .map(|c| c.to_digit(10).unwrap())
    .collect::<Vec<u32>>();

产生错误:

error[E0308]: mismatched types
 --> src/main.rs:3:20
  |
3 |       let nums: () = a
  |  ____________________^
4 | |         .chars()
5 | |         .map(|c| c.to_digit(10).unwrap())
6 | |         .collect::<Vec<u32>>();
  | |______________________________^ expected (), found struct `std::vec::Vec`
  |
  = note: expected type `()`
             found type `std::vec::Vec<u32>`
© www.soinside.com 2019 - 2024. All rights reserved.