ideasman42
ideasman42

Reputation: 48258

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. 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?

Upvotes: 9

Views: 1511

Answers (1)

DK.
DK.

Reputation: 59155

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.

Upvotes: 8

Related Questions