Mutability
mutable and imuutable types
fn main() {
let mut x = 5;
println!("the variable is mutable {x}");
let copy = x;
x = 6;
println!("the programmer changed the variable to {copy} -> {x}");
}
x 는 mutable하고 copy 는 immutable한 variable이다.
constant
const THREE_HEURES_IN_SEC: u32 = 60 * 60 * 3;
- const 는 global scope, local scope 모두 선언이 가능
- const 는 type을 동반하여 : notation으로 표기해야함.
- const 는 compile time값이며 runetime에 계산불가능. program binary에 값이 저장됨.
constant vs non-constant
let const
mutability | by adding mut | 불가능 |
type | inference가능 | explict 표현해야 |
scope | block scope (O) | |
global scope (X) | block scope (O) | |
global scope (O) | ||
memory | stack or heap | program binary |
Shadowing
fn main() {
let x = 5;
println!("after x=5: {}, {:p}",x,&x);
let x = x + 1; // new of 6, 새로운 곳에 x를 할당!
// 이전에 x=5인 곳은 접근할 수 없지만 살아있기는 함.
{
let x = x * 2;
println!("let in the block scope is {}, {:p}",x,&x);
}
println!("after x=x+1: {}, {:p}",x,&x);
println!("out of block {x}");
}
- i32 와 같은 변수는 stack에 저장된다.
- 이때 shadowing을 하면 이전 변수는 그대로 stack에 위치하고, 기존 변수 같은 이름으로 할당된다.
- 만약 block scope안에서 shadowing되면, 그 scope를 나가면 scope내 shadowing 이전의 변수로 다시 바뀐다.
- 같은 scope에서 shadowing되면 프로그램에서 참조가 불가능하다.
let spaces = " ";
let spaces = spaces.len();
GOOD
let mut spaces = " ";
spaces = spaces.len();
!!!!!!COMPILE ERROR!!!!!!
- mut 으로 선언하면 type을 변경할 수 없다.
- 대신 let 으로 같은 이름을 재활용하고 type을 변경할 수 있다.