Hi,
I am coming from C and am used to the macros basically just copy pasting code. I understand that it can cause a lot trouble, but I have some trouble understanding the way it works in Rust. I have used them for simple purposes before, but now have some trouble using them in the following case.
Currently I am trying to use a macro, that sets a struct field by calling a function choose(a, b)
. It should generate something equvalent to:
MyStruct {
field_a: choose(self.field_a().clone(), parent.field_a().clone()),
field_b: choose(self.field_b().clone(), parent.field_b().clone()),
field_c: choose(self.field_c().clone(), parent.field_c().clone()),
field_d: choose(self.field_d().clone(), parent.field_d().clone()),
field_e: choose(self.field_e().clone(), parent.field_e().clone()),
field_f: choose(self.field_f().clone(), parent.field_f().clone()),
}
My current approach is this:
/// Generates a field using the choose function
macro_rules! choose_field {
($f:expr) => $f: choose(self.$f().clone(), parent.$f().clone())
}
MyStruct {
choose_field!(field_a),
choose_field!(field_b),
choose_field!(field_c),
choose_field!(field_d),
choose_field!(field_e),
choose_field!(field_f),
}
But the compiler complains about:
($f:expr) => $f: choose(self.$f().clone(), parent.$f().clone())
^ no rules expected this token in macro call
I dont understand why the macro can't call a function?