01
基礎
変数と可変性
Rust の変数はデフォルトで不変です — これは偶発的な変更を防ぐコアの安全機能です。値を本当に変更する必要がある場合のみ 'mut' を使用してください。'const' は明示的な型を必要としコンパイル時にインライン化され、'static' は固定メモ リアドレスと 'static ライフタイムを持ちます。
rust
let x = 5; // immutable by default
let mut y = 10; // mutable with 'mut'
y += 1; // OK, y is mutable
const MAX: u32 = 100; // compile-time constant
static GREETING: &str = "Hi"; // global static
let z: i32 = -5; // explicit type annotationシャドーイング
シャドーイングにより変数名を再利用しながら型や値を変更できます。'mut' とは異なり、シャドーイングは新しいバインディングを作成します — 新しい名前を考案せずにデータを変換(例:文字列を int に解析)するのに有用です。古い値は新しいバインディング後にドロップされます。
rust
let x = 5;
let x = x * 2; // shadow previous x, now 10
let x = "text"; // can even change type!
println!("{}", x); // "text"
// shadowing vs mut: shadowing creates a NEW variable
// with the same name, allowing type changesコメントと出力
アイテムドキュメントには /// を('cargo doc' で表示)、モジュール/クレートドキュメントには //! を使用します。println! は stdout へ、eprintln! は stderr へ書き込みます。{} プレースホルダはフォーマット指定をサポートします:> は右揃え、< は左揃え、^ は中央、.N は精度、#b/#o/#x は2進/8進/16進です。
rust