相关疑难解决方法(0)

有没有办法用宏来计算?

我想创建一个指定次数打印"Hello"的宏.它的使用方式如下:

many_greetings!(3);  // expands to three `println!("Hello");` statements
Run Code Online (Sandbox Code Playgroud)

创建该宏的天真方式是:

macro_rules! many_greetings {
    ($times:expr) => {{
        println!("Hello");
        many_greetings!($times - 1);
    }};
    (0) => ();
}
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用,因为编译器不计算表达式; $times - 1不计算,但作为一个新的表达式输入宏.

macros rust rust-macros

14
推荐指数
3
解决办法
2112
查看次数

标签 统计

macros ×1

rust ×1

rust-macros ×1