相关疑难解决方法(0)

如何将标识符 (`proc_macro::Ident`) 存储为常量以避免重复?

我正在编写一个程序宏,我需要多次发出一个很长的标识符(可能是因为卫生,例如)。我quote!用来创建TokenStreams,但我不想一遍又一遍地重复长标识符!

例如,我想生成此代码:

let very_long_ident_is_very_long_indeed = 3;
println!("{}", very_long_ident_is_very_long_indeed);
println!("twice: {}", very_long_ident_is_very_long_indeed + very_long_ident_is_very_long_indeed);
Run Code Online (Sandbox Code Playgroud)

我知道我可以创建一个Ident并将其插入到quote!

let my_ident = Ident::new("very_long_ident_is_very_long_indeed", Span::call_site());
quote! {
    let #my_ident = 3;
    println!("{}", #my_ident);
    println!("twice: {}", #my_ident + #my_ident);
}
Run Code Online (Sandbox Code Playgroud)

到目前为止一切顺利,但我需要在我的代码库中的许多函数中使用该标识符。我希望它是const我可以在任何地方使用的。但是,这失败了:

const FOO: Ident = Ident::new("very_long_ident_is_very_long_indeed", Span::call_site());
Run Code Online (Sandbox Code Playgroud)

出现此错误:

let very_long_ident_is_very_long_indeed = 3;
println!("{}", very_long_ident_is_very_long_indeed);
println!("twice: {}", very_long_ident_is_very_long_indeed + very_long_ident_is_very_long_indeed);
Run Code Online (Sandbox Code Playgroud)

我怀疑这些功能是否会const很快被标记。

我可以使字符串本身成为一个常量:

const IDENT: &str = "very_long_ident_is_very_long_indeed";
Run Code Online (Sandbox Code Playgroud)

但是无论我想在哪里使用标识符,我都需要调用Ident::new(IDENT, Span::call_site()),这会很烦人。我只想写#IDENT在我的quote! …

rust rust-proc-macros

4
推荐指数
1
解决办法
308
查看次数

标签 统计

rust ×1

rust-proc-macros ×1