宏可以与常量参数而不是文字匹配吗? [英] Can macros match against constant arguments instead of literals?
问题描述
给出宏匹配示例,该示例显示了宏如何匹配一个论点.
我在这里做了一些小的改动以使用数字:
macro_rules! foo {
(0 => $e:expr) => (println!("mode X: {}", $e));
(1 => $e:expr) => (println!("mode Y: {}", $e));
}
fn main() {
foo!(1 => 3);
}
作品,印刷:mode Y: 3
但是我想使用常量作为参数,这可以使它起作用吗?
const CONST: usize = 1;
macro_rules! foo {
(0 => $e:expr) => (println!("mode X: {}", $e));
(1 => $e:expr) => (println!("mode Y: {}", $e));
}
fn main() {
foo!(CONST => 3);
}
在Rust中有可能吗?
请注意,对我而言,不能使用常规的match
语句,因为在我的代码中,每个分支都解析为不同的类型,从而产生错误.
因此,我特别想知道是否可以将常量传递给宏.
否.
宏在抽象语法树上运行,因此它们在语法层次上进行推理:他们对令牌及其拼写进行推理. >
例如:
fn main() {
let v = 3;
}
在这种情况下,AST将类似于:
fn main
\_ let-binding v
\_ literal 3
如果您问一个宏v
是否是3
,它将使您看起来很滑稽,并且想知道为什么您要尝试比较变量名和文字.
Given the macro matching example, this shows how macros can match an argument.
I've made very minor changes here to use numbers:
macro_rules! foo {
(0 => $e:expr) => (println!("mode X: {}", $e));
(1 => $e:expr) => (println!("mode Y: {}", $e));
}
fn main() {
foo!(1 => 3);
}
Works, printing: mode Y: 3
However I would like to use a constant as an argument, can this be made to work:
const CONST: usize = 1;
macro_rules! foo {
(0 => $e:expr) => (println!("mode X: {}", $e));
(1 => $e:expr) => (println!("mode Y: {}", $e));
}
fn main() {
foo!(CONST => 3);
}
Is this possible in Rust?
Note, using a regular match
statement isn't usable for me, since in my code each branch resolves to different types, giving an error.
So I'm specifically interested to know if a constant can be passed to a macro.
No.
Macros operate on the Abstract Syntax Tree, so they reason at the syntactic level: they reason about tokens and their spelling.
For example:
fn main() {
let v = 3;
}
In this case, the AST will look something like:
fn main
\_ let-binding v
\_ literal 3
If you ask a macro whether v
is 3
, it will look at you funny, and wonder why you would try comparing a variable name and a literal.
这篇关于宏可以与常量参数而不是文字匹配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!