Querying a vector of struct in Rust

Viewed 607

I am having a struct as below. I need to filter data from this struct for 2 scenario's

pub struct Access {
    role: String,
    users: Vec<String>,
}

pub struct Department_Access {
    department: String,
    department_id: String,
    access: Vec<Access>,
}

Scenario 1

I am getting dept id and user (single user) as input which i should filter all departments respective user contains access and return whole data to UI. i tried this as below and its throwing error as "expected bool, found `core::iter::adapters::Filter<IntoIter, fn(&Access) -> bool>". How to do this in efficient way ?

  let access_data = get_access_data();
    let user_access: Vec<ent::Department_Access> = access_data
        .into_iter()
        .filter(|r| r.department_id == dept_id)
        .into_iter()
        .filter(|a| a.access.into_iter().filter(|b| b.members.contains(user)))
        .collect();

Scenario 2

In another functionality, i am receiving user and department alone as a param which should query in above struct and return all department_id he had access to, which i struggling to do the basic form of query, Need your help in querying the same as well! Thanks in Advance

1 Answers

You want to use any:

    let user_access: Vec<Department_Access> = access_data
        .into_iter()
        .filter(|r| r.department_id == dept_id)
        .filter(|a| a.access.iter().any(|b| b.users.contains(&user)))
        .collect();

Also keep in mind that into_iter consumes the value; you want to use iter() only in a filter.

Related