gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:27:54 24 4
gpt4 key购买 nike

我有以下代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com