Rust中的C表达式是否等效?
int x;
while ((x = get_num()) < 5) {
printf("x is %d, but less than 5\n", x);
}
get_num()
是一个接受用户输入并返回整数的函数。
到目前为止,我能想到的最好的方法是:
while let Some(x) = {let y = get_num(); if y < 5 {Some(y)} else {None}} {
println!("x is {}, but less than 5", x);
}
答案 0 :(得分:2)
从Rust 1.28开始,您可以使用iter::repeat_with
:
for x in iter::repeat_with(get_num).take_while (|x| *x < 5) {
println!("x is {}, but less than 5", x);
}
但无聊可能更好:
loop {
let x = get_num();
if x >= 5 {
break;
}
println!("x is {}, but less than 5", x);
}
Eventually, there might在语法上应等效。
// doesn’t exist yet!
while let x = get_num() && x < 5 {
println!("x is {}, but less than 5", x);
}