Returning ref to variable on the stack?!

I suppose this is quite a basic question, but I am very confused -- how come this function compiles (foo_ref)?

Here is how I understand it:

  1. foo_ref creates a Foo struct on the stack
  2. foo_ref does not return a copy of the struct (since its signature demands a ref)
  3. So foo_ref returns a reference, but it is a reference to a variable on the stack -- how is this possible?

Is there some coercion/magic here?

struct Foo<'a> {
    name: &'a str,
}

fn foo_ref<'a> () -> &'a Foo<'a> {
    &Foo{
        name: "Alice"
    }
}

fn use_foo_ref() {
    println!("{}", foo_ref().name);
}

The variable is a compile-time constant, and does not end up on the stack. It compiles to something like this:

struct Foo<'a> {
    name: &'a str,
}

static ALICE: Foo<'static> = Foo { name: "Alice" };

fn foo_ref<'a> () -> &'a Foo<'a> {
    &ALICE
}

fn use_foo_ref() {
    println!("{}", foo_ref().name);
}
2 Likes

Thank you! I am still not crazy

This feature is called "static promotion" and it is described in RFC #1414.

3 Likes