首页 文章

这个Rust宏有什么问题?

提问于
浏览
3

我正在尝试通过将类型包装在某个变体中来编写一个为枚举生成 From impl的宏 .

我想出了这个:

macro_rules! variant_derive_from {
    ($enum:ty:$variant:ident($from:ty)) => {
        impl From<$from> for $enum {
            fn from(thing: $from) -> $enum { return $enum::$variant(thing) }
        }
    };
}

但是,每当我尝试实际使用此宏时,我会收到以下错误:

error: expected expression, found `B`
|             fn from(thing: $from) -> $enum { $enum::$variant(thing) }
|                                               ^^^^

我无法弄清楚为什么会发生这种情况,所以我运行了一个带有宏跟踪的构建,宏显然扩展到以下(虚拟类型,当然):

impl From < A > for B { fn from ( thing : A ) -> B { B :: AVariant ( thing ) } }

将此直接粘贴到代码中时,它会成功编译 . 是什么赋予了??

Here's a full example of the error.

1 回答

  • 1

    ty 占位符仅用作类型,而不是命名空间 . 使用 ident 代替应该在您的示例中正常工作 .

    ident 虽然不接受 path (“ foo::Bar ”)(并且在这种情况下使用 path 似乎也不起作用);你应该能够通过手动构建匹配它的路径来解决它: $enum:ident $(:: $enum_path:ident)* (使用它像这样: $enum $(:: $enum_path)* ) .

相关问题