t_wの輪郭

Feedlyでフォローするボタン

rustc –explain E0106

2022/2/24 12:56:00

This error indicates that a lifetime is missing from a type. If it is an error inside a function signature, the problem may be with failing to adhere to the lifetime elision rules (see below).

Erroneous code examples:

struct Foo1 { x: &bool }
              // ^ expected lifetime parameter
struct Foo2<'a> { x: &'a bool } // correct

struct Bar1 { x: Foo2 }
              // ^^^^ expected lifetime parameter
struct Bar2<'a> { x: Foo2<'a> } // correct

enum Baz1 { A(u8), B(&bool), }
                  // ^ expected lifetime parameter
enum Baz2<'a> { A(u8), B(&'a bool), } // correct

type MyStr1 = &str;
           // ^ expected lifetime parameter
type MyStr2<'a> = &'a str; // correct

Lifetime elision is a special, limited kind of inference for lifetimes in function signatures which allows you to leave out lifetimes in certain cases.
For more background on lifetime elision see [the book][book-le].

The lifetime elision rules require that any function signature with an elided output lifetime must either have:

  • exactly one input lifetime
  • or, multiple input lifetimes, but the function must also be a method with a &self or &mut self receiver

In the first case, the output lifetime is inferred to be the same as the unique input lifetime. In the second case, the lifetime is instead inferred to be the same as the lifetime on &self or &mut self.

Here are some examples of elision errors:

// error, no input lifetimes
fn foo() -> &str { }

// error, `x` and `y` have distinct lifetimes inferred
fn bar(x: &str, y: &str) -> &str { }

// error, `y`'s lifetime is inferred to be distinct from `x`'s
fn baz<'a>(x: &'a str, y: &str) -> &str { }

[book-le]: https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision

このエラーは、ある型に生存期間がないことを示します。関数シグネチャ内のエラーの場合、生存期間消去のルール(下記参照)を守らなかったことが問題である可能性があります。

エラーとなるコード例

struct Foo1 { x: &bool }.
              // ^ 生存期間パラメータが期待される
struct Foo2<'a> { x: &'a bool }. // 正しい

struct Bar1 { x: Foo2}
              // ^^^^ 生存期間パラメータが期待される
struct Bar2<'a> { x: Foo2<'a> } // 正しい

enum Baz1 { A(u8), B(&bool), }.
                  // ^ 生存期間パラメータが期待される
enum Baz2<'a> { A(u8), B(&'a bool), }. // 正しい

type MyStr1 = &str;
           // ^ 生存期間パラメータが期待される
タイプ MyStr2<'a> = &'a str; // 正解

生存期間消去は、関数シグネチャの生存期間に関する特別で限定的な推論で、特定のケースで生存期間を省くことができる。
生存期間消去の背景については、[the book][book-le] を参照してください。

生存期間消去の規則では、出力生存期間が省略された関数署名は、以下のいずれかを持っていなければならないとされています。

  • ちょうど1つの入力生存期間
  • または、複数の入力生存期間があるが、その関数が &self または &mut self レシーバを持つメソッドであること。

最初のケースでは、出力生存期間は一意の入力生存期間と同じであると推論される。2番目のケースでは、生存期間は &self または &mut self の生存期間と同じであると推論されます。

以下は消去エラーの例です。

// エラー, 入力生存期間がない
fn foo() -> &str { }.

// エラー, `x` と `y` の生存期間が異なることが推測される
fn bar(x: &str, y: &str) -> &str { }.

// error, `y` の生存期間は `x` の生存期間とは異なることが推測される。
fn baz<'a>(x: &'a str, y: &str) -> &str { }.

[book-le]: https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision