【问题标题】:What does "autoref" mean in rust?rust 中的“autoref”是什么意思?
【发布时间】:2022-07-22 16:08:02
【问题描述】:

我看到一个编译错误:

cannot infer an appropriate lifetime for autoref due to conflicting requirements

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

【问题讨论】:

    标签: rust


    【解决方案1】:

    当您尝试使用方法语法调用具有值的函数时会发生自动引用,但该函数采用&self&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();
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-02
      • 2020-06-20
      • 1970-01-01
      • 2016-09-21
      • 2023-01-19
      • 1970-01-01
      • 2015-11-01
      相关资源
      最近更新 更多