Rust 中的“autoref”是什么意思?

dip*_*pea 2 rust

我看到一个编译错误,内容如下:

cannot infer an appropriate lifetime for autoref due to conflicting requirements
Run Code Online (Sandbox Code Playgroud)

我可以在互联网上找到很多关于此错误的其他解释,但有一部分我仍然不清楚:“autoref”在这种情况下意味着什么?

cdh*_*wie 7

当您尝试使用方法语法来调用具有值的函数时,会发生 Autoref,但该函数采用&selfor &mut self-- 方法接收器会自动引用,而不是通过值给出。例如:

struct Foo;

impl Foo {
    pub fn by_value(self) {}
    pub fn by_ref(&self) {}
    pub fn by_mut(&mut self) {}
}

fn main() {
    let foo = Foo;

    // Autoref to &mut.  These two lines are equivalent.
    foo.by_mut();
    Foo::by_mut(&mut foo);

    // Autoref to &.  These two lines are equivalent.
    foo.by_ref();
    Foo::by_ref(&foo);

    // No autoref since self is received by value.
    foo.by_value();
}
Run Code Online (Sandbox Code Playgroud)

因此,在您的情况下,您正在做类似的事情,但编译器无法为不会导致借用检查问题的引用提供生命周期。