当在宏中使用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
参数构造一个结构体?