Why this code can be compiled?

#[derive(Debug)]
pub struct S {
    a: i32,
    b: f32,
}

pub fn create_s<'a>() -> &'a S {
    &S { a: 1, b: 1. }
}

fn main() {
    let a = create_s();
    println!("a: {:?}", a)
}

playground

Is the code &S{a: 1, b: 1.} different with let s = S{a: 1, b: 1.}; &s ? Very confused...

This is constant promotion, and yes it is different than let s = ...; &s, more like static PROMOTED: S = ...; &PROMOTED.

3 Likes

Thanks!

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.