Filtering a Vec of structs

I have a HashMap of a String and a Vec<Struct> and after retreiving a value from the hashmap I want to perform some filtering to check if a particular value exists among the Struct fields of the Structs in the Vec

pub struct Row {
  byte: String,
  unicode: String,
}

let mut mapping = HashMap::new();
let mut x = Vec::new();
let some = Row { byte: String::from("10"), unicode: String::from("1f440") };
let some2 = Row{ byte: String::from("11"), unicode: String::from("1f440") };
x.push(some);
x.push(some2);
mapping.insert("tom", x);

let mut val = mapping.get(&"tom")
then perform filtering to find out if the key "10" exists in the Vec of structs

val is still an Option like that. You’ll need to handle the option to access the contained &Vec<Row>. After that, if you’re just interested in (as a boolean) whether or not any struct contains a value "10" in e.g. its byte field, you can use the Iterator::any method, like this:

if let Some(v) = val { // handle the Option some way…
    let found: bool = v.iter().any(|row| row.byte == "10");
    // ... use the information

    println!("val was Some, found = {found:?}");
} else {
    println!("val was None");
}

If you also want to do something with the struct in the vec, if it exists, you can use e.g. Iterator::find, or if you want to handle all entries that contain the key, you can work with Iterator::filter.

if let Some(v) = val { // handle the Option some way…
    let found: Option<&Row> = v.iter().find(|row| row.byte == "10");
    // ... use the information

    println!("val was Some, found = {found:?}");
} else {
    println!("val was None");
}

(playground)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.