2
fn main() {
    let b = foo();
    println!("{}", b.getProp());
}

struct A {
    prop: isize
}

struct B<'a> {
    a: &'a A
}

impl<'a> B<'a> {
    fn getProp(&self) -> isize {
        return self.a.prop;
    }
}
fn foo<'a>() -> B<'a> {
    return B {
        a: &(A {
            prop: 3
        })
    };
}

This works,

fn foo<'a>() -> B<'a> {
    let a = A {
        prop: 3
    };
    return B {
        a: &(a)
    };
}

but this one doesn't work.

I already know that it is not able to return reference, but why there is a difference in these two codes?

lunuy lunuy
  • 429
  • 3
  • 7
  • 4
    Probably due to [rvalue static promotion](https://rust-lang.github.io/rfcs/1414-rvalue_static_promotion.html), where references to constant values can be promoted to have a `'static` lifetime. However, putting the value in a variable stops the promotion from happening and runs into issues where you return a reference to a local variable. – Aplet123 Mar 29 '21 at 01:44
  • that not a thing you often want to do expect very few exception you will almost never do something similar. – Stargateur Mar 29 '21 at 01:50

0 Answers0