rust 遍历Vec< &str>,并在条件满时将值累加到变量中

6ie5vjzr  于 2023-10-20  发布在  其他
关注(0)|答案(2)|浏览(132)

我目前的尝试:

let fruits:Vec<&str> = vec!["Banana", "Peach"];
let fruits_hashmap: HashMap<_, _> = HashMap::from_iter([("Apple", 2),("Banana", 4),("Peach", 8)]);
let mut n = 0;
let c =  fruits.iter().map(|s| 
    
    match fruits_hashmap.get(s) {
        Some(value) => n |= value,
        None => println!("{} does not exist", s)
    });
return n;

但我得到warning: unused variable: fruits_hashmap,n也等于0,但它应该等于12。

oknwwptz

oknwwptz1#

我猜你添加了let c =,因为你之前有另一个警告:

warning: unused `Map` that must be used
  --> src/lib.rs:8:5
   |
8  | /     fruits.iter().map(|s| match fruits_hashmap.get(s) {
9  | |         Some(value) => n |= value,
10 | |         None => println!("{} does not exist", s),
11 | |     });
   | |______^
   |
   = note: iterators are lazy and do nothing unless consumed
   = note: `#[warn(unused_must_use)]` on by default
help: use `let _ = ...` to ignore the resulting value
   |
8  |     let _ = fruits.iter().map(|s| match fruits_hashmap.get(s) {
   |     +++++++

然而,这不是解决办法。正如警告所说,iterators are lazy and do nothing unless consumed。你需要的不是map(),而是一个for循环:

for s in &fruits {
    match fruits_hashmap.get(s) {
        Some(value) => n |= value,
        None => println!("{} does not exist", s),
    }
}
ds97pgxw

ds97pgxw2#

map创建了一个新的迭代器,但实际上并没有对它进行编译:这就是为什么fruits_hashmap没有被使用。你可以 * 使用这个迭代器,然后用for循环将它重新编译,或者收集它,但是,最好避免map中的副作用。可以使用for_each

fruits.iter().for_each(|s| {
    match fruits_hashmap.get(s) {
        Some(value) => n |= value,
        None => println!("{} does not exist", s)
    }
});

相关问题