Reputation: 16158
struct Foo{
value: i32
}
impl Foo{
fn get_and_change_value(&mut self) -> i32{
let v = self.value;
self.value = 42;
v
}
}
//glue_code_macro
fn main(){
let mut f1 = Foo{value:1};
let mut f2 = Foo{value:2};
let mut f3 = Foo{value:3};
let v: Vec<i32> = glue_code_macro!(f1,f2,f3);
}
I want to create the glue_code_macro
which takes n
variables and creates a vector. I don't think that I can achieve this with a normal function because I have a mutable reference and I would be unable to change its content.
In my head it would expand to
let v = {
let v1 = f1.get_and_change_value();
let v2 = f2.get_and_change_value();
let v3 = f3.get_and_change_value();
vec!(v1,v2,v3)
}
Is this possible? If yes how would I do this?
Upvotes: 2
Views: 96
Reputation: 16660
It's possible. Add this to the top of your module:
#![feature(macro_rules)]
macro_rules! glue_code_macro(
($($element:ident),*) => (
vec![$($element.get_and_change_value(),)*]
)
)
The macro guide explains how it works: http://doc.rust-lang.org/guide-macros.html
Upvotes: 3