How to use type (ty) inside a macro to create a struct instance in Rust?

When used tyin a macro, this works in almost all the cases I tried. However, it seems that it cannot be used to declare a new instance struct.

eg: $my_type { some_member: some_value }

More detailed 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);

Error:

error: expected expression, found `MyStruct`

Changing tyto exprmeans that I cannot use impl $my_type.

Besides passing in 2x arguments one a to tyanother a expr:

Is there a way to build a structure based on an argument tyfor a macro?

+4
source share
1 answer

No, not with ty.

ident , . - , , , , ( ) ( ) .

+3

Source: https://habr.com/ru/post/1665292/


All Articles