Why can't I use the `ty` macro to build the structure?

struct A {
    x: i64,
}

macro_rules! foo {
    ($T:ty) => {
        fn test() -> $T {
            $T { x: 3 }
        }
    }
}

foo!(A);

      

Playground

error: expected expression, found `A`
8 |             $T { x: 3 }

      

I know I can use ident

, but I don't understand why I cannot use $T {}

.

+3


source to share


1 answer


Because Foo

in is Foo { bar: true }

not a type. A type is something like i32

or String

, of course, but also something like Vec<u8>

or Result<Option<Vec<bool>>, String>

.

It wouldn't make sense to write code like this:

struct A<T>(T);

fn main() {
    A<u8>(42);
}

      

You will need to pass in both the ID and the type:



macro_rules! foo {
    ($T1: ty, $T2: ident) => {
        fn test() -> $T1 {
            $T2 { x: 3 }
        }
    }
}

foo!(A, A);

      

Or you can cheat and use the token tree:

macro_rules! foo {
    ($T: tt) => {
        fn test() -> $T {
            $T { x: 3 }
        }
    }
}

      

+3


source







All Articles