2

Why is not ok to return a local variable reference but a local reference is ok or a reference to a local reference is ok?

Not OK?

fn produce_ref<'a>() -> &'a i32 {
    let v = 200;
    &v
}

But this is...


fn produce_ref<'a>() -> &'a i32 {
    let v = &200;
    v
}

or this


fn produce_ref<'a>() -> &'a i32 {
    let v = &200;
    &v
}
0xedb
  • 354
  • 2
  • 8

1 Answers1

0

For the reference to be returned, it needs to reference a point in memory which isn't freed at the end of the execution of the function.

In the first case you're returning a reference to a value which is on the stack. Such value is usually there because it's dynamically produced. This value is going away when your function ends so the reference points towards nothing then, it's not valid anymore.

In the second and third case, you're returning a reference to a literal, that is to a part of the application's binary. This value isn't going away so the reference is valid. An equivalent of those cases would be

const V: i32 = 200;

fn produce_ref<'a>() -> &'a i32 {
    let v = &V;
    &v
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • I get the first case. However, I don't get what you mean by `the value isn't going away`. – 0xedb Dec 05 '21 at 09:38
  • The value is a part of your (loaded) application binary, So this reference is just a pointer to that point in your program, it's not in the stack and won't be removed at function end. – Denys Séguret Dec 05 '21 at 09:41