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 のレビューも受けられます。
すべてのチャレンジ