変数はデフォルトでは immutable (不変)となる。
| immutable な変数の値を変更したときのエラー |
$ cargo new --bin variables
Creating binary (application) `variables` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
$ cd variabless
$ ... ← エディタで src/main.rs を編集する
$ cargo runs
Compiling variables v0.1.0 (/mnt/hostos/www/html/lec/rust/doc_rust_self/ch03/variables)
error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:4:5
|
2 | let x = 5;
| - first assignment to `x`
3 | println!("The values of x is : {}", x);
4 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
2 | let mut x = 5;
| +++
For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables` (bin "variables") due to 1 previous error |
| variables/src/main.rsを変更する |
fn main() {
let x = 5;
println!("The values of x is : {}", x);
x = 6; // ここでエラー
println!("The values of x is : {}", x);
}
|
x の宣言を mutable に変更する。
| mutable な変数の値は変更してもエラーにならない |
$ cargo run
Compiling variables v0.1.0 (/mnt/hostos/www/html/lec/rust/doc_rust_self/ch03/v02/variables)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.06s
Running `target/debug/variables`
The values of x is : 5
The values of x is : 6
|
| variables/src/main.rsを変更する |
*** v01/variables/src/main.rs Sun Jan 25 10:45:02 2026
--- v02/variables/src/main.rs Sun Jan 25 10:51:19 2026
***************
*** 1,6 ****
fn main() {
! let x = 5;
println!("The values of x is : {}", x);
! x = 6; // ここでエラー
println!("The values of x is : {}", x);
}
--- 1,6 ----
fn main() {
! let mut x = 5;
println!("The values of x is : {}", x);
! x = 6; // エラーにならない
println!("The values of x is : {}", x);
}
|
const キーワードで宣言し、値の型は必ず記述する必要がある。
(例) const MAX_POINTS: u32 = 100_000;a
(例)
let x = 5;
let x = x + 1;
{
let x = x * 2;
println("{}", x); // 12
}
println("{}", x); // 6
let guess: u32 = "42".parse().expect("Not a number");
| Length | Signed | Unsigned |
|---|---|---|
| 8-bit | i8 | u8 |
| 16-bit | i16 | u16 |
| 32-bit | i32 | u32 |
| 64-bit | i64 | u64 |
| 128-bit | i128 | u128 |
| Architecture-dependent | isize | isize |
| Number literals | Example |
|---|---|
| Decimal | 98_222 |
| Hex | 0xff |
| Octal | o0o77 |
| Binary | 0b1111_0000 |
| Byte (u8 only) | b'A' |