在宏中使用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
参数构造结构? 最佳答案
不,不是ty
。
简单的解决方法是捕获一个ident
,这在两种情况下均有效。如果您需要比简单标识符更复杂的内容,则可能需要分别捕获名称(用于构造)和类型(用于其他用途),并在使用时同时指定它们。
关于macros - 如何在宏中使用类型(ty)在Rust中构造一个struct实例?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41391522/