Why can't I use the `ty` macro to build the structure?
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 to share