【问题标题】:Why can I call File.take() on a reference?为什么我可以在引用上调用 File.take()?
【发布时间】: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


    【解决方案1】:

    take 方法来自 Read 特征。该特征在File 上实现,因此有一个方法File::take(self, u64) -> Take<Self>,但该特征也在&File 上实现(甚至在您链接到的页面上列出了实现)。对于那个 impl,Self 类型是 &File,所以 its take 方法需要一个引用。

    【讨论】:

    • 这也回答了我的另一个问题:“这两个impls 有什么意义?”我不知道它是这样工作的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2018-06-05
    • 2015-03-03
    相关资源
    最近更新 更多