==== シャドーイング ====
一度mutなしで宣言した変数でも、再度letを使って宣言しなおすことは可能であり、このため実質的に再代入のようなもの初期化がもう一度できます。
このことを、シャドーイングと言います。また、「新しい宣言によって、前の宣言が覆い隠された (shadowed) 」のように言います。
シャドーイングにより、それまで変数に束縛されていた値への参照がなくなります。
<syntaxhighlight lang=rust highlight='2,4' line>
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>
要するに、letによる宣言は、単に既存の同名の変数宣言を上書きできるというだけの事です。上書きしたところで、「宣言時のmutなしでは再代入できない」というルールは決して変わっていないので、再代入した内容をコンパイルしようとするとエラーになるという仕組みです。
==== 定数 ====
|