error: lifetime may not live long enough

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

パターン

パターン A

可変参照と不変

不変参照と可変参照はサブタイプについて、それぞれ共変と不変である。つまり、ST のサブタイプなら &S&T のサブタイプになるが、&mut S& 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

パターン B

型パラメタと不変

型定義における型パラメタの変性はフィールドの内容により決定される。フィールドがその型パラメタを最初から不変として扱っている場合、またはフィールドごとに扱いが異なる場合、その型パラメタは不変になる。そのため、これらの型パラメタからのサブタイプの波及を想定するとエラーになる。

サンプル

以下では、型 MyType<T> の型パラメタ T はコールバックの入力と出力の両方に使われているため不変となる。つまり、MyType<&'static str>MyType<&'a str> のサブタイプではない。そのため、前者の値を後者の値として戻している箇所でエラーになる。


fn func<'a>(arg: &'a MyType<&'static str>) -> &'a MyType<&'a str> {
	arg
}

struct MyType<T> {
    callback: fn(T) -> T,
}

error: lifetime may not live long enough
 --> src\lib.rs:2:5
  |
1 | fn func<'a>(arg: &'a MyType<&'static str>) -> &'a MyType<&'a str> {
  |         -- lifetime `'a` defined here
2 |     arg
  |     ^^^ returning this value requires that `'a` must outlive `'static`
  |
  = note: requirement occurs because of the type `MyType<&str>`, which makes the generic argument `&str` invariant
  = note: the struct `MyType<T>` is invariant over the parameter `T`
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance