我想创建一个指定次数打印"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
不计算,但作为一个新的表达式输入宏.
是否可以编写一个在迭代器上折叠的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的经验...