手続き型マクロを作成していて、非常に長い識別子を複数回発行する必要があります (たとえば、衛生上の理由による可能性があります)。以前は sをquote!作成してTokenStreamいましたが、長い識別子を何度も繰り返したくありません。
たとえば、次のコードを生成したいとします。
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);
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);
}
ここまでは順調ですが、コード ベース全体の多くの関数でその識別子を使用する必要があります。constどこでも使えるものにしたい。ただし、これは失敗します。
const FOO: Ident = Ident::new("very_long_ident_is_very_long_indeed", Span::call_site());
このエラーで:
error[E0015]: calls in constants are limited to constant functions, tuple structs and tuple variants
--> src/lib.rs:5:70
|
5 | const FOO: Ident = Ident::new("very_long_ident_is_very_long_indeed", Span::call_site());
| ^^^^^^^^^^^^^^^^^
error[E0015]: calls in constants are limited to constant functions, tuple structs and tuple variants
--> src/lib.rs:5:20
|
5 | const FOO: Ident = Ident::new("very_long_ident_is_very_long_indeed", Span::call_site());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
constこれらの関数がすぐにマークされるとは思えません。
文字列自体を定数にすることができます。
const IDENT: &str = "very_long_ident_is_very_long_indeed";
しかし、識別子を使用したい場合はどこでも を呼び出す必要がありIdent::new(IDENT, Span::call_site())、これはかなり面倒です。呼び出しに書きたいだけです#IDENT。quote!どうにかして機能させることはできますか?