我想添加一些syn::Ident
来形成&'static str
。所有Ident
都应为concat,以形成一个逗号分隔和字符串化(因为这是我得到Ident
的字符串表示的方式)&'static str
。
我在这里遇到了一个无法正常工作的项目:https://github.com/Jasperav/comma_separated(在example
文件夹中,测试失败)。
这是我的测试:
#[test]
fn test_another_struct() {
assert_eq!("name, another_name", AnotherStruct::useless())
}
由于以下原因而失败:
Expected :nameanother_name Actual :name, another_name
这是我的代码试图生成逗号分隔的列表(在
lib.rs
内部):let idents = vec![
syn::Ident::new("name", Span::call_site()),
syn::Ident::new("another_name", Span::call_site())
];
proc_macro::TokenStream::from(quote! {
impl #struct_name {
fn useless() -> &'static str {
concat!(#(stringify!(#idents)),*)
}
}
})
我不明白为什么它不起作用。我的宏中有1个
,
,这意味着:用逗号分隔所有内容,对吗?
最佳答案
如果您对代码进行cargo expand
编码,那么您会意识到自己已扩展为:
(假设struct_name
是Foo
)
impl Foo {
fn useless() -> &'static str {
concat!(stringify!(name), stringify!(another_name))
}
}
stringify!
将ident直接转换为字符串,所以返回的值等于
concat!("name", "another_name")
在这里,逗号是语法的分隔符,而不是字符串文字,
所以你最终得到
nameanother_name
。仅考虑上面的代码,最方便的解决方法是在proc_macro代码中编写原始字符串
而不是依赖
stringify!
和concat!
,允许您使用
slice::join
之类的API。
关于rust - 逗号分隔的syn::Idents列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61660393/