Variable Bindings

Variable Bindingsを読む。

幾つか面白い動きがあった。デフォルトが書き換え不可(immutable)だからできる動きなんだろうな。

fn main() {
    /* スコープ:{} 以下でのみ有効 */
    let x: i32 = 17;
    {
        let y2: i32 = 3;
        println!("The value of x is {} and value of y2 is {}", x, y2);
    }
    // println!("The value of x is {} and value of y2 is {}", x, y2); // This won't work

    /* スコープ:同じ変数名での動き。 */
    let x2: i32 = 8;
    {
        println!("{}", x2); // Prints "8"
        let x2 = 12;
        println!("{}", x2); // Prints "12"
    }
    println!("{}", x2); // Prints "8"
    let x2 =  42;
    println!("{}", x2); // Prints "42"

    /* 型のある言語だけど、同じ名前で色々と代入できる。 */
    let y = 4;
    println!("{}", y);
    let y = "I can also be bound to text!"; // y is now of a different type
    println!("{}", y);
}