Fluent Rust - const

Migo·2023년 10월 10일
0

Fluent Rust

목록 보기
10/23
post-thumbnail

Quiz

Quick quiz! Guess what the output of the following code will be:

struct MyFanctStruct {
    f: i32,
}

const S: MyFancyStruct = MyFancyStruct { f: 1 };

fn main() {
    let fancy_struct = &mut S;
    fancy_struct.f += 1;
    S.f += 1;
    print!("{}{}", fancy_struct.f, S.f);
}

If you guessed that the answer would be 44 or the code will not compile, continue reading - that's not how const in Rust works.

Semantics of const

Every time you access const value in expression, that is replaced with the value. So the first line in the main method, becomes:

fn main(){
	let v = &mut MyFancyStruct{f:1}; 
    ...
}

Which is again, equivalent to :

fn main(){
	let mut _tmp_val = MyFancyStruct{f:1};
    let fancy_struct = &mut _tmp_val;
}

Now, in the second line,f is accessed through fancy_struct. But then the third line, when calling S, it becomes again the follwing:

fn main() {
	let mut _tmp_val = MyFancyStruct{f:1};
    let fancy_struct = &mut _tmp_val;
    fancy_struct.f += 1;
    MyFancyStruct{f:1}.f += 1; // MyFancyStruct is initialzed and goes out of scope right away! 
    
    print!("{}{}", fancy_struct.f, S.f);
}

The answer is therefore, 21

So finally, when you reach print!("{}{}", fancy_struct.f, S.f); it is essentially the same as:

	print!("{}{}", fancy_struct.f,  MyFancyStruct{f:1}.f);

Fun! isn't it?

profile
Dude with existential crisis

0개의 댓글