繁体   English   中英

无法为结构内具有相同生命周期的多个引用推断生命参数的适当生命周期 [E0495]

[英]cannot infer an appropriate lifetime for lifetime parameter with multiple references with the same lifetime inside a struct [E0495]

我在我的代码中遇到了关于生命周期推断的错误,我已经能够将代码简化为以下内容:

use std::collections::HashMap;

struct A<'a> {
    x: &'a mut HashMap<&'a str, i32>,
}

impl<'a> A<'a> {
    fn new(x: &'a mut HashMap<&'a str, i32>) -> Self {
        Self { x }
    }
    
    fn test(&mut self) {
        let a = A::new(self.x);
    }
}

fn main() {
}

由此产生的错误是

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
  --> src/main.rs:13:17
   |
13 |         let a = A::new(self.x);
   |                 ^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 12:5...
  --> src/main.rs:12:5
   |
12 | /     fn test(&mut self) {
13 | |         let a = A::new(self.x);
14 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:13:24
   |
13 |         let a = A::new(self.x);
   |                        ^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 7:6...
  --> src/main.rs:7:6
   |
7  | impl<'a> A<'a> {
   |      ^^
note: ...so that the expression is assignable
  --> src/main.rs:13:24
   |
13 |         let a = A::new(self.x);
   |                        ^^^^^^
   = note: expected `&mut std::collections::HashMap<&str, i32>`
              found `&mut std::collections::HashMap<&'a str, i32>`

我不明白这种情况下的错误是什么,但我确实发现,如果我将生命周期'b添加到struct A中,这样HashMap中的str引用的生命周期为'b ,代码就会编译。 以下是上述更改后代码的样子:

use std::collections::HashMap;

struct A<'a, 'b> {
    x: &'a mut HashMap<&'b str, i32>,
}

impl<'a, 'b> A<'a, 'b> {
    fn new(x: &'a mut HashMap<&'b str, i32>) -> Self {
        Self { x }
    }
    
    fn test(&mut self) {
        let a = A::new(self.x);
    }
}

fn main() {
}

但是,我不知道为什么这种改变有效。 据我了解,两个生命周期都是'a意味着 A 必须与HashMap一样长,而HashMap必须与用作其键的&str一样长,我认为这没有问题。 我也看不到更改如何为编译器添加任何附加信息。 谁能帮我解释一下这种情况?

A::test() function 更改为

fn test(&'a mut self) { // Add lifetime specification
    let a = A::new(self.x);
}

它应该工作。

编译器说它无法推断A::new()的生命周期,第一个注释提到“匿名生命周期”,这意味着编译器不知道A::new(self.x)self.x的生命周期。 所以我们只需要告诉编译器self的生命周期为'a

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM