如何在 Rust 中使用宏中的类型(ty)构造结构体实例?

9

当在宏中使用ty时,我尝试过的几乎所有情况都可以工作。但是,似乎不能用它来声明一个新的struct实例。

例如:$my_type { some_member: some_value }

下面是一个更全面的示例:

macro_rules! generic_impl {
    ($my_type:ty) => {
        impl $rect_ty {
            pub fn flip(&self) -> $my_type { self.some_method() }
            pub fn swap(&self, &other: $my_type) -> { self.some_swap_method(other) }
            // so far so good!

            // now our troubles start :(
            pub fn create(&self) -> $my_type {
                return $my_type { foo: 1, bar: 2, baz: 2 };
                //     ^^^^^^^^ this fails!!!
            }
        }
    }
}

// example use
generic_impl(MyStruct);
generic_impl(MyOtherStruct);

错误信息如下:
error: expected expression, found `MyStruct`

ty更改为expr意味着我不能使用impl $my_type

除了传入两个参数,一个是ty,另一个是expr

是否有一种方法可以基于宏的ty参数构造一个结构体?

1个回答

8
不,不能使用 ty
简单的解决方法是捕获一个 ident,它在两个上下文中都有效。如果你需要比一个简单标识符更复杂的内容,那么你可能需要分别捕获名称(用于构建)和类型(用于其他用途),并在使用时同时指定它们。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接