首页 > 解决方案 > 通过两个向量嵌套for循环

问题描述

我在 Rust 中想要这样的东西,但我不明白编译错误:

fn main() {
    let apple: String = String::from("apple");
    let accle: String = String::from("accle");

    let apple_vec: Vec<char> = apple.chars().collect();
    let accle_vec: Vec<char> = accle.chars().collect();
    
    let counter = 0;
    for j in accle_vec {
        for i in apple_vec {
          // if i == j{ 
            counter++;
          // }
        }
    }
    println!("counter is {}", counter);
}

我想一一比较两个数组的字符,每次出现不匹配的时候计数。

标签: rust

解决方案


这里发生了几件事,所以让我们分解一下。

我们遇到的第一个错误是:

error: expected expression, found `+`
  --> src/main.rs:12:21
   |
12 |             counter++;
   |                     ^ expected expression

error: could not compile `playground` due to previous error

这意味着这是无效的语法。那是因为 rust 没有++,而是我们可以使用counter += 1or counter = counter + 1。我会用第一个。

进行此更改时,我们会遇到一些错误,但专注于counter,我们会看到:

error[E0384]: cannot assign twice to immutable variable `counter`
  --> src/main.rs:12:13
   |
8  |     let counter = 0;
   |         -------
   |         |
   |         first assignment to `counter`
   |         help: consider making this binding mutable: `mut counter`
...
12 |             counter += 1;
   |             ^^^^^^^^^^^^ cannot assign twice to immutable variable

Some errors have detailed explanations: E0382, E0384.
For more information about an error, try `rustc --explain E0382`.

我们得到的建议是合理的——计数器被声明为不可变的,我们正试图改变它。我们应该将其声明为可变的。所以let mut counter = 0

最后,我们得到以下错误:

error[E0382]: use of moved value: `apple_vec`
   --> src/main.rs:10:18
    |
5   |     let apple_vec: Vec<char> = apple.chars().collect();
    |         --------- move occurs because `apple_vec` has type `Vec<char>`, which does not implement the `Copy` trait
...
10  |         for i in apple_vec {
    |                  ^^^^^^^^^
    |                  |
    |                  `apple_vec` moved due to this implicit call to `.into_iter()`, in previous iteration of loop
    |                  help: consider borrowing to avoid moving into the for loop: `&apple_vec`
    |
note: this function takes ownership of the receiver `self`, which moves `apple_vec`

这是因为以这种方式迭代内部向量会在第一遍中耗尽它,而在外部循环的第二遍中,内部迭代是不可能的。为了防止这种情况,您可以借用 vec 进行迭代,而不是像for i in &apple_vec

将所有这些放在一起将产生以下代码:

fn main() {
    let apple: String = String::from("apple");
    let accle: String = String::from("accle");

    let apple_vec: Vec<char> = apple.chars().collect();
    let accle_vec: Vec<char> = accle.chars().collect();
    
    let mut counter = 0;
    for j in &accle_vec {
        for i in &apple_vec {
           if i == j {
                counter += 1;
           }
        }
    }
    println!("counter is {}", counter);
}

推荐阅读