error[E0515]: cannot return value referencing local variable `var`

error[E0515]: cannot return reference to function parameter `arg`

error[E0515]: cannot return reference to temporary value

関数が参照型を戻す場合、参照先は関数からの復帰後も有効でなければならない。

そのため、ローカル変数、関数の引数、一時的な値、これらは戻り値にできない。

パターン

パターン A

ローカル変数

以下では、戻り値にローカル変数への参照が含まれている。


fn test() -> &'static i32 {
    let var = 0;
    &var
}

error[E0515]: cannot return reference to local variable `var`
 --> src\lib.rs:3:5
  |
3 |     &var
  |     ^^^^ returns a reference to data owned by the current function

パターン B

関数の引数

以下では、戻り値に引数への参照が含まれている。


fn test(arg: i32) -> &'static i32 {
    &arg
}

error[E0515]: cannot return reference to function parameter `arg`
 --> src\lib.rs:2:5
  |
2 |     &arg
  |     ^^^^ returns a reference to data owned by the current function

パターン C

一時的な値

以下では、戻り値に一時的な値への参照が含まれている。


fn test(arg: i32) -> &'static i32 {
    &(arg + 1)
}

error[E0515]: cannot return reference to temporary value
 --> src\lib.rs:2:5
  |
2 |     &(arg + 1)
  |     ^---------
  |     ||
  |     |temporary value created here
  |     returns a reference to data owned by the current function