rust - 有没有办法将类型名称放入 Rust 宏中?

标签 rust

我有以下代码:

trait Trait {
    const NAME: &'static str;
    const VALUE: i64;
}

struct Struct1 {}
struct Struct2 {}

impl Trait for Struct1 {
    const NAME: &'static str = "Aardvark";
    const VALUE: i64 = 0;
}

impl Trait for Struct2 {
    const NAME: &'static str = "Zebra";
    const VALUE: i64 = 100;
}

macro_rules! print_static {
    ($n:expr, $v:expr) => {
        println!("Value of {} is {}", $n, $v);
    };
}

macro_rules! print_static2 {
    ($t:expr) => {
        println!("Value of {} is {}", $t::NAME, $t::VALUE);
    };
}

fn main() {
    print_static!(Struct1::NAME, Struct1::VALUE);
    print_static!(Struct2::NAME, Struct2::VALUE);

    //print_static2!(Struct1);
    //print_static2!(Struct2);
}

它运行为:

Value of Aardvark is 0
Value of Zebra is 100

当我取消注释 print_static2 行时,我得到:

error: expected one of `,`, `.`, `?`, or an operator, found `::`
  --> src/main.rs:28:41
   |
28 |         println!("Value of {} is {}", $t::NAME, $t::VALUE);
   |                                         ^^ expected one of `,`, `.`, `?`, or an operator
...
37 |     print_static2!(Struct1);
   |     ------------------------ in this macro invocation
   |
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: expected one of `,`, `.`, `?`, or an operator, found `::`
  --> src/main.rs:28:41
   |
28 |         println!("Value of {} is {}", $t::NAME, $t::VALUE);
   |                                         ^^ expected one of `,`, `.`, `?`, or an operator
...
38 |     print_static2!(Struct2);
   |     ------------------------ in this macro invocation
   |
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

有没有办法只指定一次类型名称,这样我就不会做这样的事情?

// Incorrectly associating Struct2's value with Struct1!
print_static!(Struct1::NAME, Struct2::VALUE);

Rust Playground

最佳答案

如果你想把一个类型作为参数,那么说:

macro_rules! print_static {
    ($t:ty) => {
        println!("Value of {} is {}", <$t>::NAME, <$t>::VALUE);
    };
}

这是 the full list of macro parameter types .

关于rust - 有没有办法将类型名称放入 Rust 宏中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64142796/

相关文章:

syntax - Rust 中的 ..=(点点等于)运算符是什么?

closures - 将 &mut 传递给函数并返回闭包的生命周期问题

rust - 为什么我共享的 actix-web 状态有时会重置回原始值?

rust - Rust 项目的推荐目录结构是什么?

rust - 在近协议(protocol)合约的函数中返回多个值

rust - #[derive(PartialEq, Eq)] 会增加代码大小吗?

c - 使用类型 `[my_struct]` 是将 C 结构数组传递给 Rust 函数的正确方法吗?

rust - 按键对数组排序时的Rust生命周期问题

recursion - 在 Rust 中编写定点函数

rust - 运行命令时如何避免僵尸进程?