error: lifetime may not live long enough

error - ライフタイムの不足』のサブタイプについての派生パターン。

背景情報

不変参照は被参照型のサブタイプが波及するが、可変参照にこの効果はない。

不変参照の場合 (共変)

S が型 T のサブタイプなら、&S&T のサブタイプになる。

なぜなら、&T からは T を取得できればよいが、&S はこれを満足できる。

可変参照の場合 (不変)

S が型 T のサブタイプでも、&mut S&mut T は互いに互いのサブタイプにならない。

なぜなら、&mut T には T を設定できなければならないが、&mut S はこれを満足できない。また、&mut SS を取得できなければならないが、&mut T はこれを満足できない。

サンプル

以下では、Ref<'static>Ref<'a> のサブタイプであるが、&'a mut Ref<'static>&'a mut Ref<'a> のサブタイプではない。そのため、前者の値を後者の値として戻している箇所でエラーになる。


fn func<'a>(arg: &'a mut Ref<'static>) -> &'a mut Ref<'a> {
    arg
}

struct Ref<'a>(&'a i32);

error: lifetime may not live long enough
 --> src\lib.rs:2:5
  |
1 | fn func<'a>(arg: &'a mut Ref<'static>) -> &'a mut Ref<'a> {
  |         -- lifetime `'a` defined here
2 |     arg
  |     ^^^ returning this value requires that `'a` must outlive `'static`
  |
  = note: requirement occurs because of a mutable reference to `Ref<'_>`
  = note: mutable references are invariant over their type parameter
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance