2013-12-08 42 views
1

我不明白为什么rustc给了我这个错误error: use of moved value: 'f'在编译时,用下面的代码:为什么我不能重用funtion的借用指针

fn inner(f: &fn(&mut int)) { 
    let mut a = ~1; 
    f(a); 
} 

fn borrow(b: &mut int, f: &fn(&mut int)) { 
    f(b); 
    f(b); // can reuse borrowed variable 

    inner(f); // shouldn't f be borrowed? 

    // Why can't I reuse the borrowed reference to a function? 
    // ** error: use of moved value: `f` ** 
    //f(b); 
} 

fn main() { 
    let mut a = ~1; 
    print!("{}", (*a)); 
    borrow(a, |x: &mut int| *x+=1); 
    print!("{}", (*a)); 
} 

我想重用我通过后关闭它作为另一个函数的参数。我不确定它是可复制还是堆栈封闭,有没有办法说明?

该代码段用于生锈0.8。我设法使用最新的rustc(master:g67aca9c)编译不同版本的代码,将&fn(&mut int)更改为普通的fn(&mut int),并使用普通函数而不是闭包,但是如何才能使用闭包来处理此问题?

+0

我已阅读[防锈闭锁侦探工作](http://blog.pnkfx.org/blog/2013/06/07/detective-work-on-rust-closures/),但我不太清楚还没完成。 –

回答

1

事情的实质是,&fn在正常意义上实际上不是借来的指针。这是一个封闭类型。在master中,函数类型已经被修复了很多,并且这种事情的语法已经改变为|&mut int| - 如果你想要一个借用函数指针,目前你需要输入它&(fn (...))&fn现在被标记为过时的语法,帮助人们远离它,因为它是完全不同的类型)。

但是对于关闭,您可以通过引用将它们传递给:&|&mut int|

+0

我明白了,这个[snippet does work](https://gist.github.com/hackaugusto/7864860),谢谢 –

相关问题