为什么不能使用`ty` 宏匹配器构造结构体?

3
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 }

我知道我可以使用 ident,但是我不明白为什么不能使用$T {}

1个回答

3
因为在 Foo { bar: true }中的 Foo 不是一种类型。类型像是 i32 或者 String,当然也可以像是 Vec<u8> 或者 Result<Option<Vec<bool>>, String> 这样的。

这样写代码就没有任何意义:

struct A<T>(T);

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

您需要传入标识符类型

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

foo!(A, A);

或者您可以通过使用令牌树来作弊:
macro_rules! foo {
    ($T: tt) => {
        fn test() -> $T {
            $T { x: 3 }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接