如何从 Rust 的闭包内部跳过循环迭代?
How do I skip a loop iteration from inside a closure in Rust?
我正在学习如何在 Rust 中使用闭包并想到了这个:
fn main() {
repeat_five_times(&|i: usize| {
println!("{}", i);
})
}
fn repeat_five_times(each: &dyn Fn(usize) -> ()) {
for i in 0..5 {
each(i)
}
}
这是输出:
0
1
2
3
4
repeat_five_times
函数显然将传递的代码重复五次并且运行良好。
我想在 i
达到 3
时从闭包内部跳过迭代:
fn main() {
repeat_five_times(&|i: usize| {
if i != 3 {
println!("{}", i);
}
else {
continue
}
})
}
我希望输出如下所示:
0
1
2
4
这不会编译,说 'continue' inside of a closure; cannot 'continue' inside of a closure
。
我应该怎么做才能跳过迭代?我还可以做些什么来完全停止循环?
闭包中没有控制流,因此您不能在闭包中使用控制流关键字。如果您只是删除 continue
它会按预期工作:
fn main() {
repeat_five_times(|i: usize| {
if i != 3 {
println!("{}", i);
}
});
}
fn repeat_five_times(each: fn(usize)) {
for i in 0..5 {
each(i)
}
}
如果您想跳出循环,您必须以某种方式将该信息从您的闭包传达给您的循环。一种简单的方法是让闭包 return 成为 bool
,它表示上一次迭代是否成功并且迭代是否应该继续。示例:
fn main() {
// closure returns true when to continue iterating
// but returns false when the loop should be stopped
repeat_five_times(|i: usize| {
println!("{}", i);
i < 3 // returns false on 3 or higher
});
}
fn repeat_five_times(each: fn(usize) -> bool) {
for i in 0..5 {
if !each(i) { // break if current iteration failed processing
break;
}
}
}
我正在学习如何在 Rust 中使用闭包并想到了这个:
fn main() {
repeat_five_times(&|i: usize| {
println!("{}", i);
})
}
fn repeat_five_times(each: &dyn Fn(usize) -> ()) {
for i in 0..5 {
each(i)
}
}
这是输出:
0
1
2
3
4
repeat_five_times
函数显然将传递的代码重复五次并且运行良好。
我想在 i
达到 3
时从闭包内部跳过迭代:
fn main() {
repeat_five_times(&|i: usize| {
if i != 3 {
println!("{}", i);
}
else {
continue
}
})
}
我希望输出如下所示:
0
1
2
4
这不会编译,说 'continue' inside of a closure; cannot 'continue' inside of a closure
。
我应该怎么做才能跳过迭代?我还可以做些什么来完全停止循环?
闭包中没有控制流,因此您不能在闭包中使用控制流关键字。如果您只是删除 continue
它会按预期工作:
fn main() {
repeat_five_times(|i: usize| {
if i != 3 {
println!("{}", i);
}
});
}
fn repeat_five_times(each: fn(usize)) {
for i in 0..5 {
each(i)
}
}
如果您想跳出循环,您必须以某种方式将该信息从您的闭包传达给您的循环。一种简单的方法是让闭包 return 成为 bool
,它表示上一次迭代是否成功并且迭代是否应该继续。示例:
fn main() {
// closure returns true when to continue iterating
// but returns false when the loop should be stopped
repeat_five_times(|i: usize| {
println!("{}", i);
i < 3 // returns false on 3 or higher
});
}
fn repeat_five_times(each: fn(usize) -> bool) {
for i in 0..5 {
if !each(i) { // break if current iteration failed processing
break;
}
}
}