宏可以匹配常量参数而不是文字吗? [英] Can macros match against constant arguments instead of literals?

查看:11
本文介绍了宏可以匹配常量参数而不是文字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定宏匹配示例,这显示了宏如何匹配一个论点.

为了使用数字,我在这里做了很小的改动:

macro_rules!富{(0 => $e:expr) =>(println!("模式 X: {}", $e));(1 => $e:expr) =>(println!("mode Y: {}", $e));}fn 主(){foo!(1 => 3);}

作品,打印:mode Y: 3

但是我想使用一个常量作为参数,这是否可行:

const CONST: usize = 1;宏规则!富{(0 => $e:expr) =>(println!("模式 X: {}", $e));(1 => $e:expr) =>(println!("mode Y: {}", $e));}fn 主(){foo!(CONST => 3);}

这在 Rust 中可行吗?

<小时>

注意,使用常规的 match 语句对我来说不可用,因为在我的代码中,每个分支都解析为不同的类型,从而产生错误.所以我特别想知道是否可以将常量传递给宏.

解决方案

没有

宏在抽象语法树上运行,因此它们在句法级别进行推理:它们对标记和它们的拼写进行推理.>

例如:

fn main() {让 v = 3;}

在这种情况下,AST 将类似于:

fn main\_ 让绑定 v\_ 文字 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆