Better way of iterating vector and comparing values

struct Foo{
    name:String,
    val:String,
}
fn main(){

    let bar = vec![ Foo{name:"ab".to_owned(),val:"val1".to_owned()},
                Foo{name:"cd".to_owned(),val:"val2".to_owned()},
                Foo{name:"ef".to_owned(),val:"val3".to_owned()},
                ];

    let mut z = "".to_string(); //line 12
    for a in bar {
        if a.name == "cd" {
              z = a.val;
              break;
        }
    }; //line 18
    
    println!("{:?}",z);
}

is there any better way of writing the code from line no 12 to 18 in a single line?

let z = bar.iter().find(|a| a.name == "cd").unwrap_or("")
You're right, @diva123. It should be let z = bar.iter().find(|a| a.name == "cd").map_or_else(|| String::default(), |a| a.val.clone())

4 Likes

Or .unwrap_or_default().

i think here find() returns option .but How z will have "val" here ?