How to put a field of struct as parameter of a function?

Hello all,

I'm starting with rust following the rust book and doing some small project to practice, and I found something that I can't get done, that I m sure more experience user will know. I would like to pass on a function the field of a struct. for example, I have these 2 struct and impl.

pub struct Data{
client: String,
country: String,
city:String,
}

pub struct V_Data{
vector: Vec,
}

impl V_Data {
pub fn insert_data(&mut self,data:Data){
self.vector.push(data);
}

pub fn show_data_by_client(&self){
    for i in self.vector.iter(){
        println!("{}",i.client); 
    }
}

pub fn show_data_by_country(&self){
    for i in self.vector.iter(){
        println!("{}",i.country); 
    }
}

pub fn show_data_by_city(&self){
for i in self.vector.iter(){
println!("{}",i.city);
}
}

}

so, what I would like to have instead of 3 functions show_data_by_client, show_data_by_country and show_data_by_city one that would be show_data_by_field and something like this.

pub fn show_data_by_city(&self, field:&str){
for i in self.vector.iter(){
println!("{}",i.field);
}
}

but of course this is not working since is not a string reference, is there a way to do put a field of a stuct ?

Thank you so much in advance.

Generalize the functions by taking a closure callback:

impl V_Data {
    fn show_data_by<'a, F: FnMut(&'a Data) -> T, T: std::fmt::Display>(&'a self, mut callback: F) {
        for i in self.vector.iter() {
            println!("{}", callback(i));
        }
    }
}

fn main() {
    let v = V_Data { ... };
    v.show_data_by(|data| &data.client);
    v.show_data_by(|data| &data.country);
    v.show_data_by(|data| &data.city);
}

Side note: when you are posting code on this forum, use the fenced code block syntax of Markdown to get a nice syntax highlighting and formatting:

```rust
Paste your code here
```
1 Like

Thank you so much pcpthm for you answer.