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

时间:2016-12-30 06:15:09

标签: macros rust

在宏中使用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

除了传递2x参数外,还有一个ty另一个expr

有没有办法根据宏的ty参数构造一个结构?

1 个答案:

答案 0 :(得分:5)

不,不是ty

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