4 ms·
In the example given the macro is almost useless. The benefit comes if you want the expanded code to have more things, like methods defined that otherwise you w
by estebank 7y ago
In the example given the macro is almost useless. The benefit comes if you want the expanded code to have more things, like methods defined that otherwise you would have your consumer write or sister methods and types.
The macros are only about convenience on usage and reduction of boilerplate. A good example is the vec![1,2] macro call that expands to
{
let mut x = Vec::new();
x.push(1);
x.push(2);
x
}
The reason the blog post is using that example is because it's showing a new type of macro argument which accepts items (functions, structs, enums, traits and impls) and expands them correctly without any extra needs by the macro writer.
- cesarb 7y agoJust nitpicking, but a better explanation of the expansion of `vec![1,2]` would use `Vec::with_capacity(2)` instead of `Vec::new()`, that is, it already allocates the Vec with the correct capacity (the real expansion uses in-place construction of a boxed slice, but the effect is similar).