error: lifetime may not live long enough

長いライフタイムが必要な箇所に短いライフタイムの値を使用した。

サンプル

以下では、str のライフタイムは self.0 より短いかもしれない。


fn main() {
    let mut max = Max("");
    max.swap("hoge");
    max.swap("piyo");
    max.swap("fuga");
    assert_eq!(max.0, "piyo");
}

struct Max<'a>(&'a str);

impl Max<'_> {
    fn swap<'x>(&mut self, x: &'x str) {
        if self.0 < x {
            self.0 = x;
        }
    }
}

error: lifetime may not live long enough
  --> src/main.rs:14:13
   |
12 |     fn swap<'x>(&mut self, x: &'x str) {
   |             --  --------- has type `&mut Max<'1>`
   |             |
   |             lifetime `'x` defined here
13 |         if self.0 < x {
14 |             self.0 = x;
   |             ^^^^^^^^^^ assignment requires that `'x` must outlive `'1`

解決策

ライフタイムどうしの関係を明示するといい。


以下では、x のライフタイムが self.0 のライフタイムを囲むようにしている。


fn main() {
    let mut max = Max("");
    max.swap("hoge");
    max.swap("piyo");
    max.swap("fuga");
    assert_eq!(max.0, "piyo");
}

struct Max<'a>(&'a str);

impl<'a> Max<'a> {
    fn swap<'x: 'a>(&mut self, x: &'x str) {
        if self.0 < x {
            self.0 = x;
        }
    }
}

派生パターン