Search in a complex structure

Hello.
How to find an element in a complex structure?

Code:

#[derive(Clone, Debug)]
pub struct Element {
    pub name: String,
    pub foo: String,
}

#[derive(Debug)]
pub struct CustomStruct {
   pub name: String,
   pub cs_elements: Vec<Element>
}

pub struct Config {
   pub config_elements: Vec<CustomStruct>
}

fn main() 
{
  let mut cs1 = CustomStruct{name : "cs1".to_string(), cs_elements : Vec::new()};

  let cs1_e1 = Element{ name : "cs1_e1".to_string(), foo : "xxx".to_string()};
  let cs1_e2 = Element{ name : "cs1_e2".to_string(), foo : "yyy".to_string()};

  cs1.cs_elements.push(cs1_e1);

  let mut cfg = Config{config_elements : Vec::new()};
  cfg.config_elements.push(cs1);
}

For example : I would like found element = cs1_e2

let f_element = cfg
    .config_elements
    .iter()
    .filter_map(|s| s.cs_elements.iter().find(|x| x.name == find_name))
    .next()
    .unwrap();

Playground

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.