Is it possible to emit Rust attributes from within macros?

后端 未结 1 1898
长发绾君心
长发绾君心 2020-12-11 23:09

I\'m trying to do something like the following:

macro_rules! attr_trial {
    ($msg:expr) => {{
        let id = env!(\"SOME_ENV\");

        #[link_secti         


        
相关标签:
1条回答
  • 2020-12-11 23:50

    Is it possible to emit Rust attributes from within macros?

    Absolutely, it is possible. Here's a macro that emits a test attribute from within a macro:

    macro_rules! example {
        () => {
            #[test]
            fn test() {
                assert!(false);
            }
        };
    }
    
    example!();
    

    It's not possible in all contexts, however. For example, you can't emit just an attribute because the attribute is expected to be attached to an item:

    macro_rules! example {
        () => {
            #[test]
        };
    }
    
    // Fails!
    example!();
    fn test() {
        assert!(false);
    }
    

    Your actual question is closer to "is it possible to call a macro inside of an attribute". The answer to that appears to be no - the parser does not expect a macro expansion in that location. Perhaps you want to look at code generation or procedural macros, depending on what you are trying to do.

    0 讨论(0)
提交回复
热议问题