Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
935 views
in Technique[技术] by (71.8m points)

rust - Why can I call File.take() on a reference?

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...