ANimator120
ANimator120

Reputation: 3441

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

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"]
}

Upvotes: 2

Views: 1657

Answers (1)

pretzelhammer
pretzelhammer

Reputation: 15165

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

Upvotes: 4

Related Questions