I was surprised to discover that this code works and I'm not sure why:
struct Bar;
struct Foo {
bar: Bar,
}
fn new_foo<'a>() -> &'a Foo {
&Foo { bar: Bar }
}
It looks like a dangling reference, as we just created a Foo and returned a reference to it, but the compiler lets it go so where is the Foo after that call?
Note that understandably, returning something like &Foo::new() doesn't work
It's called "static promotion" (google this expression to learn more). Certain simple expressions (eg. integer literals but also your trivial struct construction) can implicitly be stored in static memory because they are known at compile time, and then taking their address yields a reference that's valid for any lifetime.
There’s also a single type that supports this for mutable reference: Empty arrays. (In principle, this could be sound with mutable references for any zero-sized type.)
fn empty<'a, T>() -> &'a mut [T; 0] {
&mut []
}
This can occasionally be useful, especially if you use it as a slice, &mut [T]. On a similar note, &mut [T] implements Default (the implementation uses this feature internally, too), and thus also supports mem::take, powering code such as