为什么我可以在引用上调用 File.take() ? [英] Why can I call File.take() on a reference?
问题描述
当我查看 File
的文档,我看到 take
方法采用 self
,而不是 &self
.但是我仍然可以在借用的引用上调用该方法:
fn foo(file: &File) {让 _ = file.take(1);//为什么这样做?println!("仍然可以使用文件:{:?}", file);}
我认为 self
会传递所有权,但我什至可以在调用 take
后使用 file
,因此所有权显然保留在 中foo
.
如果我自己使用方法在自定义结构上执行此操作,则不起作用:
struct Foo;impl Foo {fn foo(self: foo) { }}fn 主(){让 foo = &Foo;foo.foo();//错误:无法移出借用的内容}
完全符合预期.
同样,根据文档,File
据我所知没有实现任何特殊特征.引起我注意的是 Read
有一个 by_ref()
方法,但我没有调用它但一切仍然有效.
这是怎么回事?(使用 rustc 1.3.0-dev)
take
方法来自 Read
特性.该特性在 File
上实现,因此有一个方法 File::take(self, u64) ->以<Self>
为例,但该特征也在 &File
上实现(该实现甚至列在您链接到的页面上).对于那个实现,Self
类型是 &File
,所以 its take
方法需要一个引用.>
When I look at File
's docs, I see that the take
method takes a self
, not a &self
. But I'm still able to call the method on a borrowed reference:
fn foo(file: &File) {
let _ = file.take(1); // why does this work?
println!("can still use the file: {:?}", file);
}
I thought a self
passes ownership but I'm even able to use file
after calling take
so ownership clearly stays inside foo
.
If I do it myself on a custom struct with a method, it doesn't work:
struct Foo;
impl Foo {
fn foo(self: Foo) { }
}
fn main() {
let foo = &Foo;
foo.foo(); // error: cannot move out of borrowed content
}
which is fully expected.
Likewise according to the docs, File
does not implement any special traits as far as I can tell. What did get my attention is that Read
has a by_ref()
method but I don't call it yet everything still works.
What's going on here? (using rustc 1.3.0-dev)
The take
method comes from the Read
trait. That trait is implemented on File
, so there is a method File::take(self, u64) -> Take<Self>
, but the trait is also implemented on &File
(the impl is even listed on the very page you link to). For that impl, the Self
type is &File
, so its take
method takes a reference.
这篇关于为什么我可以在引用上调用 File.take() ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!