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
,这在两种情况下均有效。如果您需要比简单标识符更复杂的内容,则可能需要分别捕获名称(用于构造)和类型(用于其他用途),并在使用时同时指定它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句