Rust 기초
Rust Variables, mut, const and Shadowing
Variables in Rust cannot change unless you ask. Learn let, let mut, const and shadowing.
배울 내용
- let and let mut
- Constants with const
- Shadowing a variable
Declaration → what it allows
let language = "Rust"cannot changelet mut score = 10can changeconst MAX_SCORE: u32 = 100fixed for the whole programlet score = score * 2 → a new variable, 30
Immutable by default
Variables in Rust cannot change unless you say so. let creates a variable, let mut creates one you can change, and const creates a value that is fixed for the whole program.
score is declared with mut, so score += 5 is allowed. The second let score creates a new variable with the same name, which is called shadowing. The braces in println! print the variables named inside them.
핵심 포인트
- let creates a variable that cannot change.
- let mut allows the value to change.
- A second let with the same name creates a new variable (shadowing).
실행 가능한 Rust 예제
Rust
main.rs
fn main() {
let language = "Rust";
let mut score = 10;
score += 5;
const MAX_SCORE: u32 = 100;
let score = score * 2; // shadowing creates a new variable
println!("{language}: {score} of {MAX_SCORE}");
}
Rust: 30 of 100연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- Swap First and Last Exchange the first and last items of a list. 쉬움
- Running Sum Replace each value with the total so far. 쉬움