In my project I'm frequently iterating through a vector of structs to find an object by some field value, then use some trait function on that object:
pub struct Person{
name: String,
age: u32,
id: u32,
}
impl Person{
pub fn new(name: String, id_num: u32, age: u32)->Self{
let p = Person{
name: name,
id: id_num,
age: age,
};
p
}
}
trait PersonTrait{
fn printname();
fn get_name()->String;
fn get_age()->u32;
fn set_age(age: u32);
}
impl PersonTrait for Person{
fn printname(){
dbg!(self.name)
}
fn get_name()->String{
self.name
}
fn get_id()->u32{
self.id;
}
fn set_age(age: u32){
self.age = age;
}
}
fn main(){
let my_people = vec![Person::new("Rakim".to_string(), 1, 56), Person::new("Ghostface".to_string(), 2, 56), Person::new("RZA".to_string(), 3, 56)];
//frequently repeating this pattern of finding struct in array of structs, then doing something to that found struct
for person in my_people.clone(){
if person.get_id() == 1 {
person.set_age(100);
}
}
for person in my_people.clone(){
if person.get_id() == "Rakim".to_string(){
person.printname();
}
}
}
So the general pattern im using here is:
for x in my_objects{
if x.id() == some_id{
x.do_some_trait_function()
}
}
I'd like to create a more general function to make this syntax simpler, something like:
//not sure what the correct syntax would be here, or how you might pass a trait function as an argument
fn find_then_do_trait_function(obj_list: Vec<Person>, id: u32, trait_function: my_trait_function()){
for x in obj_list(){
if x.get_id() == id {
//use my trait function on x
}
}
}
How might I do this? I know I could create an enum
for every trait function, then match
that enum, but that also seems pretty verbose.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…