Perl日記

日々の知ったことのメモなどです。Perlは最近やってないです。

Rust で変数の宣言と値の束縛は別々にできるらしい

let での変数宣言と値の束縛は、特に mut ではなくても、別でも良いらしい。
const は一緒にやらないとだめらしい。

    let x: i32;
    x = 123;
    println!("x: {}", x);

    // Compile Error!
    // const C: i32;
    // C = 123;
    // println!("{}", C);
x: 123

これはスコープ内であれば、別のブロックでも値の束縛ができるらしい。
変数宣言時に型を明記しなくても、束縛時の型推論は動作するらしい。

    let y;
    if x > 100 {
        y = 234;
    } else {
        y = 345;
    }
    println!("y: {}", y);
y: 234

しかし、Go 言語のゼロ値のように、未定義時の値というものはないので、使用しようとするとコンパイルエラーになる。

    let z: i32;
    println!("{}", z);
error[E0381]: borrow of possibly-uninitialized variable: `z`
   --> src\main.rs:376:24
    |
376 |         println!("{}", z);
    |                        ^ use of possibly-uninitialized `z`
    |
    = note: this error originates in the macro `$crate::format_args_nl` (in Nightly 
builds, run with -Z macro-backtrace for more info)


参考
宣言 - Rust By Example 日本語版