[英]How to use a type (ty) within a macro to construct a struct instance in Rust?
When using ty
in a macro, this works in nearly all cases I've tried. 在宏中使用
ty
时,这几乎适用于我尝试过的所有情况。 However, it seems it cant be used to declare a new struct
instance. 但是,它似乎无法用于声明新的
struct
实例。
eg: $my_type { some_member: some_value }
例如:
$my_type { some_member: some_value }
A more comprehensive example 一个更全面的例子
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);
The error is: 错误是:
error: expected expression, found `MyStruct`
Changing the ty
to an expr
means I can't use impl $my_type
. 将
ty
更改为expr
意味着我不能使用impl $my_type
。
Besides passing in 2x arguments, one a ty
the other an expr
: 除了通过在2x参数,一个是
ty
其他的expr
:
Is there a way to construct a struct based on a ty
argument to a macro? 有没有办法根据宏的
ty
参数构造一个结构?
No, not with ty
. 不,不是
ty
。
The simple fix is to capture an ident
instead, which is valid in both contexts. 简单的解决方法是捕获一个
ident
,它在两个上下文中都是有效的。 If you need something more complex than a simple identifier, then you're probably going to need to capture the name (for construction) and the type (for other uses) separately and specify them both on use. 如果您需要比简单标识符更复杂的东西,那么您可能需要分别捕获名称(用于构造)和类型(用于其他用途)并在使用时指定它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.