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);
}
从 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);
}