削除された内容 追加された内容
Ef3 (トーク | 投稿記録)
→‎変数・定数とミュータブル・イミュータブル: 「再代入」とカイていたが、最初の = は初期化なので「再」は不要だった。ミュータビリティはオブジェクトではなく束縛された変数に付与される・・・ことを書くのは所有権でまとめて説明したい。
タグ: 2017年版ソースエディター
再宣言
160 行
Hello, world!
Hello, rust!
</syntaxhighlight>
 
==== 再宣言 ====
一度mutなしで宣言した変数でも、再度letを使って宣言しなおすことは可能であり、このため実質的に再代入のようなものがもう一度できます。
 
<syntaxhighlight lang=rust highlight='2,4' line>
fn main() {
let hello : &str = "Hello, world!";
println!("{}", hello);
let hello = "Hello, rust!";
println!("{}", hello);
}
</syntaxhighlight>
;実行結果:<syntaxhighlight lang=text>
Hello, world!
Hello, rust!
</syntaxhighlight>
 
ただし、mutなしで新しく宣言された変数は最代入が禁止なので、下記のように新たにletなしで代入をするとエラーになります。
 
<syntaxhighlight lang=rust highlight='2,4' line>
fn main() {
let hello : &str = "Hello, world!";
println!("{}", hello);
let hello = "Hello, rust!";
println!("{}", hello);
let hello = "Hello, error!";
println!("{}", hello);
}
</syntaxhighlight>
;実行結果:<syntaxhighlight lang=text>
error[E0384]: cannot assign twice to immutable variable `hello`
--> sample.rs:7:5
|
4 | let hello = "Hello, rust!";
| -----
| |
| first assignment to `hello`
| help: consider making this binding mutable: `mut hello`
...
7 | hello = "Hello, mistake!";
| ^^^^^^^^^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable
 
error: aborting due to previous error
 
For more information about this error, try `rustc --explain E0384`.
 
</syntaxhighlight>