前回の続きから
1. cargo new パッケージ作成
% cargo new hello-rust
Creating binary (application) `hello-rust` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
2. cargo run パッケージビルド、実行
cd hello-rust
cargo run
# => Hello, world!
3. 実装を書き換えてみる
src/main.rsを書き換える
src/main.rs
fn main() {
println!("Hello, Wasm!");
}
cargo run
# => Hello, Wasm!
4.変数つかってみる
fn main() {
let message = "Hello, Wasm!";
println!("変数messageに束縛された値: {}", message);
}
5. 束縛について
Rustでは=演算子を使った変数と値の紐づけを束縛という。
変数は標準で変更不可(immutable)。
この辺結構特徴的だと思う(javascriptとかとごっちゃになりそう)。
fn main() {
let message = "Hello, Wasm!";
println!("変数messageに束縛された値: {}", message);
message = "Hello, World!";
println!("変数messageに束縛された値: {}", message);
}
エラーになって修正の提案をしてくれる。めちゃ優秀。
error[E0384]: cannot assign twice to immutable variable `message`
--> src/main.rs:4:3
|
2 | let message = "Hello, Wasm!";
| ------- first assignment to `message`
3 | println!("変数messageに束縛された値: {}", message);
4 | message = "Hello, World!";
| ^^^^^^^^^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
2 | let mut message = "Hello, Wasm!";
| +++
For more information about this error, try `rustc --explain E0384`.
error: could not compile `hello-rust` (bin "hello-rust") due to 1 previous error
指示されたコマンドを打ってみる
rustc --explain E0384
エラーについて解説が出てきた。すごい。
An immutable variable was reassigned.
Erroneous code example:
fn main() {
let x = 3;
x = 5; // error, reassignment of immutable variable
}
By default, variables in Rust are immutable. To fix this error, add the keyword mut after the keyword let when declaring the
variable. For example:
fn main() {
let mut x = 3;
x = 5;
}
Alternatively, you might consider initializing a new variable: either with a new bound name or (by shadowing) with the bound
name of your existing variable. For example:
fn main() {
let x = 3;
let x = 5;
}
提案された内容で修正するとエラーが出なくなる。
fn main() {
let mut message = "Hello, Wasm!";
println!("変数messageに束縛された値: {}", message);
message = "Hello, World!";
println!("変数messageに束縛された値: {}", message);
}