Search code examples
loopsrustvectorhashmap

Iterate through Vec<&str> and accumulate value to a variable when condition is fullfilled


My current attempt:

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;

But I get warning: unused variable: fruits_hashmap and also n is equal to 0 but it should be equal to 12.


Solution

  • I guess you added let c = because you had another warning before:

    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) {
       |     +++++++
    

    However, this isn't the solution. As the warning says, iterators are lazy and do nothing unless consumed. What you need is not map(), but a for loop:

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