是否可以从宏内部发出Rust属性? [英] Is it possible to emit Rust attributes from within macros?

查看:106
本文介绍了是否可以从宏内部发出Rust属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行以下操作:

I'm trying to do something like the following:

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

        #[link_section = env!("SOME_ENV")]
        static MESSAGE: &'static str = $msg;
    }};
}

然后出现以下错误:

error: unexpected token: `env`
  --> src/main.rs:34:18
   |
34 |            #[link_section = env!("SOME_ENV")]
   |                           ^

推荐答案

是否可以从宏内部发出Rust属性?

Is it possible to emit Rust attributes from within macros?

绝对,这是可能的.这是一个从宏内部发出test属性的宏:

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!();

但是,并非在所有情况下都可行.例如,您不能发出 just 属性,因为该属性应附加到项目上:

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);
}


您的 actual 问题更接近是否可以在属性内部调用宏".答案似乎是-解析器不希望该位置进行宏扩展.也许您想查看代码生成或过程宏,具体取决于您要执行的操作.


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.

这篇关于是否可以从宏内部发出Rust属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆