Search code examples
loopsrustvector

Iterate over a Vector with condition and return the second item of Vector/Tuple


Despite the numerous examples on internet I could not figure out this one:

How to iterate over a Vector (which itself contains Vector of 2 String items) and return the second item?

My attempt (returns true, I would like to get "the result" instead)

fn main() {
     let data:Vec<Vec<&str>> = vec![vec!["b", "dummy"], vec!["c", "dummy"],vec!["r", "the result"], vec!["a", "dummy"]];
     let a = data.iter().any(|i| i.into_iter().nth(0).unwrap() == &"r");
     println!("{}",a);
}

Also I would like to consume the vector and avoid unnecessary copy, as well as stop at the first result (or when reaching end of vector if no result).

NB: I know that the inside Vector could be a tuple but I don't have control over this type of data as it is returned to me as a Vector by an API.


Solution

  • any() is the wrong tool for the job. The correct tool is find():

    let a: Option<&str> = data
        .iter()
        .find(|inner_vec| inner_vec[0] == "r")
        .map(|inner_vec| inner_vec[1]);
    println!("{:?}", a);
    

    If you have Strings in the vectors and not &str, and you want to avoid cloning, it is just a bit more complicated:

    let a: Option<String> = data
        .into_iter()
        .find(|inner_vec| inner_vec[0] == "r")
        .and_then(|inner_vec| inner_vec.into_iter().nth(1));
    println!("{:?}", a);