gpt4 book ai didi

vector - 如何从Rust的结构数组中获取字段值的数组?

转载 作者:行者123 更新时间:2023-12-03 11:30:31 25 4
gpt4 key购买 nike

我想将一个结构数组映射到一个字段值数组。我该怎么做?

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

最佳答案

您有两种可能的解决方案,具体取决于您是要克隆名称还是借用它们。以下两种解决方案:

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

关于vector - 如何从Rust的结构数组中获取字段值的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65443671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com