Do Rust macros work inside trait definitions? -
i can build structs , enums using macros not traits. bug or how traits work missing? here simple example fails build:
macro_rules! fun{ () => { fn hello(); } } macro_rules! full_fun{ () => { fn hello(){} } } // fails with: // <anon>:13:8: 13:11 error: expected 1 of `const`, `extern`, `fn`, `type`, or `unsafe`, found `fun` // <anon>:13 fun!(); macro_rules! trait_macro{ ($name:ident) => { pub trait $name { fun!(); } }; } macro_rules! struct_macro{ ($name:ident) => { pub struct $name; impl $name { full_fun!(); } }; } // can add functions impl struct_macro!{monster} // cannot add functions trait trait_macro!{monster} fn main() { }
according the rust documentation on macros, macro can expanded as:
- zero or more items
- zero or more methods,
- an expression,
- a statement, or
- a pattern.
your full_fun
becomes method, think declaration inside trait doesn't count. (i haven't found exact reference, though).
even if were, wouldn't help: due macro hygiene rules, hello
defined couldn't referenced elsewhere, unique identifier different other - ie fun!()
macro not declaring same function implemented full_fun!()
.
Comments
Post a Comment