Can someone please explain why returning a reference to a new struct from a fn is possible in this simple scenario? Is my assumption correct that static promotion is making this possible here (1414-rvalue_static_promotion - The Rust RFC Book )?
This is the working cargo run
example:
main.rs:
struct BStruct {
data: u32,
}
fn new_b_struct<'a>() -> &'a BStruct {
&BStruct { data: 42 }
}
fn main() {
let b_struct = new_b_struct();
assert_eq!(b_struct.data, 42);
}
jbe
December 12, 2022, 11:09am
2
I think that &BStruct { data: 42 }
is of type &'static BStruct
. And &'a BStruct
is a supertype of &'static struct
.
Compare:
struct BStruct {
data: u32,
}
fn new_b_struct() -> &'static BStruct {
&BStruct { data: 42 }
}
fn main() {
let b_struct = new_b_struct();
assert_eq!(b_struct.data, 42);
}
(Playground )
And yes, if I understand it correctly, then static promotion happens here:
&BStruct { data: 42 }
1 Like
Thank you very much for your quick answer, confirmation and added remarks!
system
Closed
March 12, 2023, 11:26am
4
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.