这个 Rust 宏有什么问题?

Alp*_*der 7 macros rust

我正在尝试编写一个宏,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) }
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

impl From < A > for B { fn from ( thing : A ) -> B { B :: AVariant ( thing ) } }
Run Code Online (Sandbox Code Playgroud)

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

这是错误的完整示例。

Ste*_*fan 4

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

ident但不接受paths (" foo::Bar") (并且 usingpath在这种情况下似乎也不起作用);您应该能够通过手动构建路径来解决这个问题,例如匹配:($enum:ident $(:: $enum_path:ident)*像这样使用它$enum $(:: $enum_path)*:)。