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 S
は 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