Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a type (ty) within a macro to construct a struct instance in Rust?

Tags:

macros

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?

like image 269
ideasman42 Avatar asked Dec 30 '16 06:12

ideasman42


1 Answers

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.

like image 107
DK. Avatar answered Oct 31 '22 13:10

DK.