How to get Array of Field Values from Array of Structs in Rust?

Viewed 629

I'd like to map an array of structs to an array of field values. How would I do this?

pub struct Person {
    name: String
} 

fn main() {
    let my_people = vec![
        Person {
            name: "Bob".to_string(),
        },
        Person {
            name: "Jill".to_string(),
        },
        Person {
            name: "Rakim".to_string(),
        },
    ];
    //map my_people to ["Bob", "Jill", "Rakim"]
}
1 Answers

You have two possible solutions, depending on whether you want to clone the names or borrow them. Both solutions below:

pub struct Person {
    name: String,
}

fn people_names_owned(people: &[Person]) -> Vec<String> {
    people.iter().map(|p| p.name.clone()).collect()
}

fn people_names_borrowed(people: &[Person]) -> Vec<&str> {
    people.iter().map(|p| p.name.as_ref()).collect()
}

fn main() {
    let my_people = vec![
        Person {
            name: "Bob".to_string(),
        },
        Person {
            name: "Jill".to_string(),
        },
        Person {
            name: "Rakim".to_string(),
        },
    ];
    println!("{:?}", people_names_owned(&my_people));
    println!("{:?}", people_names_borrowed(&my_people));
}

playground

Related