相关疑难解决方法(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
查看次数

是否可以编写一个在迭代器上折叠的const函数?

是否可以编写一个在迭代器上折叠的const函数?当我尝试:

const fn foo(s: &str) -> u64 {
    return s.chars().fold(0, |accumulator, char| -> u64 {
        return accumulator ^ (char as u64);
    });
}
Run Code Online (Sandbox Code Playgroud)

我收到编译器错误:

const fn foo(s: &str) -> u64 {
    return s.chars().fold(0, |accumulator, char| -> u64 {
        return accumulator ^ (char as u64);
    });
}
Run Code Online (Sandbox Code Playgroud)

我想我的匿名函数|x, y| -> x { ... }是作为函数指针传递给的fold(),这就是导致错误的原因。

我可以传递给fold这里某种类型的const lambda吗,还是可以只使用for循环并在可变变量中累积结果,然后从foo函数中返回?我完全没有Rust的经验...

const rust

1
推荐指数
1
解决办法
381
查看次数

标签 统计

rust ×2

const ×1

macros ×1

rust-macros ×1