Rust 闭包需要对lambda函数的唯一访问
我正在学习Rust,并且已经实现了一些简单的代码来试验闭包——但是在借用检查器中遇到了一个问题,我不知道如何解决这个问题 编译以下函数时Rust 闭包需要对lambda函数的唯一访问,rust,borrow-checker,Rust,Borrow Checker,我正在学习Rust,并且已经实现了一些简单的代码来试验闭包——但是在借用检查器中遇到了一个问题,我不知道如何解决这个问题 编译以下函数时 fn twice(x:int, f:|int| -> int) -> int { f(f(x)) } 我得到以下错误 closure requires unique access to `f` but it is already borrowed 我正在阅读指南,对借阅检查人员为什么不喜欢这一点有一个适度的理解——但我不确定如何解决它
fn twice(x:int, f:|int| -> int) -> int {
f(f(x))
}
我得到以下错误
closure requires unique access to `f` but it is already borrowed
我正在阅读指南,对借阅检查人员为什么不喜欢这一点有一个适度的理解——但我不确定如何解决它
我可以先将第一次调用的结果分配给一个临时变量,然后再调用f(…)
来解决这个问题。然而,这感觉不雅
有没有更干净/更好的方法来编写
f(f(x))
,或者有什么方法可以让编译器相信这是安全的?完整的错误消息是:
<anon>:2:7: 2:8 error: closure requires unique access to `f` but it is already borrowed
<anon>:2 f(f(x))
^
<anon>:2:5: 2:6 note: previous borrow of `f` occurs here; the unique capture prevents subsequent moves or borrows of `f` until the borrow ends
<anon>:2 f(f(x))
^
<anon>:2:12: 2:12 note: previous borrow ends here
<anon>:2 f(f(x))
^
在modern Rust中,原始代码按原样编译:
fn twice(x: i32, f: impl Fn(i32) -> i32) -> i32 {
f(f(x))
}
fn main() {
twice(42, |i| dbg!(i));
}
谢谢您知道这是语言的一部分,还是借用检查器中的一个边缘情况,我们会在某个时候清理它吗?这肯定是必须解决的。@JamesDavies,主要是一个边缘情况(例如,请参阅我引用的问题)。
fn twice(x: i32, f: impl Fn(i32) -> i32) -> i32 {
f(f(x))
}
fn main() {
twice(42, |i| dbg!(i));
}