包含条件扩展的 Rust 宏

问题描述 投票:0回答:1

我想在声明性宏中仅当布尔值为

true
时才展开项目(函数或类型定义)。

我知道可以使用过程宏,但我问是否也可以仅使用声明性宏。

例如我有这个程序:

macro_rules! my_macro {
    {
        $cond1:literal,
        $cond2:literal
    } => {
        conditionally_expand! { $cond1, fn f1() { println!("1"); } }
        conditionally_expand! { $cond2, fn f2() { println!("2"); } }
    };
}


fn main() {
    my_macro!{false, true};
    //f1(); // Must be illegal
    f2(); // Must be legal
}

my_macro
接收两个文字布尔值。因为第一个是
false
,所以不应该定义函数
f1
,因为第二个是
true
,所以应该定义函数
f2
conditionally_expand
如何实现?

rust macros
1个回答
0
投票

你可以匹配文字

macro_rules! my_macro {
    {
        $cond1:literal,
        false
    } => {

    };
© www.soinside.com 2019 - 2024. All rights reserved.