Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

前方宣言

It is possible to declare variable bindings first and initialize them later, but all variable bindings must be initialized before they are used: the compiler forbids use of uninitialized variable bindings, as it would lead to undefined behavior.

It is not common to declare a variable binding and initialize it later in the function. It is more difficult for a reader to find the initialization when initialization is separated from declaration. It is common to declare and initialize a variable binding near where the variable will be used.

fn main() {
    // 変数を宣言。
    let a_binding;

    {
        let x = 2;

        // 変数を初期化。
        a_binding = x * x;
    }

    println!("a binding: {}", a_binding);

    let another_binding;

    // エラー!初期化していない変数の使用
    println!("another binding: {}", another_binding);
    // FIXME ^ この行をコメントアウトしましょう

    another_binding = 1;

    println!("another binding: {}", another_binding);
}