I have several asset types modeled as structs, e.g.
#[derive(Debug, Deserialize, Serialize)]
struct Vehicle {
short: String,
name: String,
number_plate: String,
purchase_cost: u32,
purchase_date: NaiveDate,
charge_minute: f32,
charge_km: f32,
}
The different structs have different fields, but they all have a “short” and “name” fields which implement ToString (in fact they are all Strings)
I’d like to get a Vec of (short, name) pairs, so:
fn vehicle_pairs(vs: &Vec<Vehicle>) -> Vec<(String, String)> {
vs.iter()
.map(|v| (v.short.to_string(), v.name.to_string()))
.collect::<Vec<_>>()
}
Which is fine. To generalize this function to other types, I probably need a macro since to make it generic I’d need to specify bounds that relate to fields rather than methods and I don’t believe this is possible.
I’m new to macros, just read some docs today. My first attempt:
macro_rules! pairs {
($T:ty) => {
fn get_pairs<T>(xs: &Vec<T>) -> Vec<(String, String)> {
xs.iter()
.map(|x| (x.short.to_string(), x.name.to_string()))
.collect::<Vec<_>>()
}
}
}
pairs!(Vehicle);
But this doesn’t work.
How can I create a generic function that extracts (short, name) from a struct with those fields?