为什么迭代 i32 向量会引用 i32 (&i32)?

2023-12-04

以下程序尝试对学生的成绩进行评分:

use std::io;

fn main() {
    let mut in0 = String::new();
    io::stdin().read_line(&mut in0).expect("stdin err");
    let n: i32 = in0.trim().parse().expect("parse err");
    println!("{}", n);
    let mut v: Vec<i32> = Vec::new();
    for _ in 0..n {
        let mut inp = String::new();
        io::stdin().read_line(&mut inp).expect("stdin err");
        let num: i32 = inp.trim().parse().unwrap();
        v.push(num);
    }
    let out: Vec<_> = v
        .iter()
        .map(|x| {
            if x < 38 {
                x
            } else if x % 5 > 3 {
                x + x % 5
            } else {
                x
            }
        })
        .collect();
    println!("{:?}", v);
}

编译时,我收到以下错误。

error[E0308]: mismatched types
  --> src/main.rs:19:20
   |
19 |             if x < 38 {
   |                    ^^
   |                    |
   |                    expected `&i32`, found integer
   |                    help: consider borrowing here: `&38`

error[E0308]: `if` and `else` have incompatible types
  --> src/main.rs:24:17
   |
21 |               } else if x % 5 > 3 {
   |  ____________________-
22 | |                 x + x % 5
   | |                 --------- expected because of this
23 | |             } else {
24 | |                 x
   | |                 ^ expected `i32`, found `&i32`
25 | |             }
   | |_____________- `if` and `else` have incompatible types
   |
help: consider dereferencing the borrow
   |
23 |             } else *{
24 |                 x
25 |             }

怎么样x变量a&i32类型而不是i32 type?


Calling the .iter() method on a vector returns an iterator over references the vector's elements. Otherwise, it would have to move or copy the elements out of the vector, which is not desirable in the general case [1]. In the documentation this is not immediately obvious from the declaration:

pub fn iter(&self) -> Iter<T>  // Return type does not look like a reference

但是,这些示例表明您可以获得参考:

assert_eq!(iterator.next(), Some(&1));  // note the `&1` instead of just `1`

可以指示闭包取消引用参数:

v.iter().map(|&x| { /* do something */ })

如果向量包含,那就没问题了Copy有能力的类型,例如i32。否则这会导致无法移出借用的内容错误。在这种情况下,您可能无论如何都需要使用参考。

如果迭代后不再需要向量,可以使用.into_iter(),它消耗向量并迭代拥有的项目而不是引用。

[1] Moving would clear the vector, which is covered by the .drain() method, and copying is not possible/efficient on all types.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么迭代 i32 向量会引用 i32 (&i32)? 的相关文章

随机推荐