#E0020: 尾随闭包中的 return
在语句的尾随闭包中,单独的 return 只会离开闭包,而不会离开外层的函数。用 return@name 离开闭包(name 是接收这个闭包的函数),要离开函数,则把代码写在调用之后。
nabi
fn each(xs: List<i32>, f: fn(i32) -> ()) { for x in xs { f(x); } }
fn main() {
each([1, 2, 3]) |x| {
if x == 2 { return; }
println(f"{x}");
}
}
error[E0020]: a bare `return` in a statement's trailing closure: it would leave only the closure, not the function --> main.nabi:5:21 | 5 | if x == 2 { return; } | ^^^^^^ | = help: write `return@each` to end this call of the closure; to leave the function, write a `for` loop instead of the call
用 return@each 离开闭包,名称取自接收它的函数:
nabi
fn each(xs: List<i32>, f: fn(i32) -> ()) { for x in xs { f(x); } }
fn main() {
each([1, 2, 3]) |x| {
if x == 2 { return@each; }
println(f"{x}");
}
}
1
3
相关错误码:E0059 关键字在其上下文之外
发现错误? 在 GitHub 上编辑此页 最后更新: