You can think of ident as a name of a struct or enum we're deriving the implementation for. We're getting it from the parse_macro_input! and then we u

Search code, repositories, users, issues, pull requests...

submited by
Style Pass
2025-01-14 22:00:06

You can think of ident as a name of a struct or enum we're deriving the implementation for. We're getting it from the parse_macro_input! and then we use it in the quote!, which is like a template engine for Rust code generation.

Now it's time to make our getter initializable by #[my_trait(answer = ...)] attribute. We'll need one more crate for convenient parsing of the initialization value

Struct Opts describes parameters of the #[my_trait(...)] attribute. Here we have only one of them - answer. Notice that it's optional, because we don't want to overwrite the default fn answer() implementation if the attribute wasn't used.

The quote! macro is composable - we can use output of one of them in another. So in the match we check if the initializer is passed and create the method implementation or just nothing. And finally we use the result in the outer quote! template.

Leave a Comment