Where: Struct with field

I have a multitude of different structs.
Each one have a field in common, lets say "name".
I would like to create a function that receive a Vec where T is a struct that has a key "name" and that return Vec with T name modified.
Is there a way to do that, without:

  • trait (implementing the trait for every struct seems like a lot of code for a small thing)
  • external closure (like passing ``|item: &MyStruct| item.name``` in parameter of the function)
  • unsafe

Example of ideal expectation:

fn my_fn<T>(data: Vec<T>) -> Vec<T> where T has "name" {
  let mut new_vec: Vec<T> = Vec::new();
  for item in data {
     let new_item = T {name: new_name(name), ..item};
     new_vec.push(new_item);
  }
  new_vec
}

No.

But you could implement the trait with a macro?

True.
I could implement the trait for every struct, but that seems a bit too much.
But it might be the solution that Im going for, even tho unsafe seems tempting in this case T^T

Here's an example using a macro:

trait SetName {
    fn set_name(&mut self, name: String);
}

macro_rules! impl_set_name {
    ($($name:ident),*) => {
        $(
        impl SetName for $name {
            fn set_name(&mut self, name: String) {
                self.name = name;
            }
        }
        )*
    };
}

struct MyStruct1 {
    name: String,
    foo: u32,
}
struct MyStruct2 {
    name: String,
    bar: u32,
}
struct MyStruct3 {
    name: String,
    foo: u32,
    baz: String,
}

impl_set_name!(MyStruct1, MyStruct2, MyStruct3);

I don't even know how you would do it, even with unsafe.

2 Likes