【发布时间】:2015-10-08 19:18:16
【问题描述】:
当我查看File's docs 时,我看到take 方法采用self,而不是&self。但我仍然可以在借用的引用上调用该方法:
fn foo(file: &File) {
let _ = file.take(1); // why does this work?
println!("can still use the file: {:?}", file);
}
我认为self 传递了所有权,但我什至可以在调用take 后使用file,因此所有权显然保留在foo 中。
如果我自己在带有方法的自定义结构上执行此操作,则它不起作用:
struct Foo;
impl Foo {
fn foo(self: Foo) { }
}
fn main() {
let foo = &Foo;
foo.foo(); // error: cannot move out of borrowed content
}
完全符合预期。
同样,据我所知,File 没有实现任何特殊特征。引起我注意的是 Read 有一个 by_ref() 方法,但我没有调用它,但一切仍然有效。
这里发生了什么? (使用 rustc 1.3.0-dev)
【问题讨论】:
标签: rust