rust - 逗号分隔的syn::Idents列表

标签 rust rust-macros

我想添加一些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_nameFoo)

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/

相关文章:

rust - 如何从上面文件夹中的另一个文件夹导入函数

compiler-errors - 在编译时发出警告?

rust - 如何在rust宏中从 “Bar”获得 “Foo::Bar”?

type-conversion - 在 Rust 中创建类型之间的自定义转换的标准方法是什么?

struct - 如何为字段值为另一个结构的结构实现 rustc_serialize::Decodable?

macos - Rust macOS pkg 安装程序安装到哪里?

rust - 在编译时计算一组常量表达式的最大值

module - 如何跨模块文件使用宏?

rust - 让GtkComboBox条目为Pixbuf或String