When using ty
in a macro, this works in nearly all cases I've tried.
However, it seems it cant be used to declare a new struct
instance.
eg: $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
.
Besides passing in 2x arguments, one a ty
the other an expr
:
Is there a way to construct a struct based on a ty
argument to a macro?
No, not with ty
.
The simple fix is to capture an ident
instead, which is valid in both contexts. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With