DEV Community

Discussion on: References to Literals in Rust?!

Collapse
 
chayimfriedman2 profile image
Chayim Friedman • Edited

Note this is not the only promotion in Rust: even code like let x = &"abc".to_owned(); works, even though "abc".to_owned() is not a constant expression and cannot be promoted into a constant. Or let x = &mut 0;, since constant promotion does not work with mutable references (rightfully). What takes place here is temporary lifetime extension, and the compiler extends the lifetime of the temporary to the whole block, like you wrote:

let __temp = "abc".to_owned();
let x = &__temp;
dbg!(x);
Enter fullscreen mode Exit fullscreen mode

Another static promotion, even preceding the static promotion RFC, is empty array static promotion: you can do &mut [], even though you cannot do that for any other type, including ZSTs (let x: &'static mut () = &mut (); is an error, but let x: &'static mut [i32; 0] = &mut [] compiles).