本文へスキップ
BecomeCoder

Rustのエラー · エラー9

E0106: missing lifetime specifier ― ライフタイムの指定漏れ

参照を返す関数で、その参照が「どの引数の借用に由来するか」をコンパイラが判断できない場合に出ます。

出るコード

fn longer(a: &str, b: &str) -> &str {   // 戻り値のライフタイム不明
    if a.len() > b.len() { a } else { b }
}

エラーメッセージ

error[E0106]: missing lifetime specifier
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`

直し方

fn longer<'a>(a: &'a str, b: &'a str) -> &'a str のように、引数と戻り値に同じライフタイム 'a を明示します。