2

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 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

A third option could be to consume the person list in the process and return owned Strings without needing to clone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.