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

ide*_*n42 6 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);
Run Code Online (Sandbox Code Playgroud)

错误是:

error: expected expression, found `MyStruct`
Run Code Online (Sandbox Code Playgroud)

改变为我无法使用tyexpr手段impl $my_type.

除了传递2x参数,一个是ty另一个expr:

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

DK.*_*DK. 5

不,不是ty.

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