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

定数

Rust には、グローバルを含む任意のスコープで宣言できる 2 種類の定数があります。どちらも明示的な型注釈が必要です。

  • const: 変更できない値(一般的なケース)。
  • static: 'static ライフタイムを持つ、可変である可能性のある変数。 static ライフタイムは推論されるため、指定する必要はありません。 可変 static 変数にアクセスまたは変更することは unsafe です。
// グローバルは他のすべてのスコープの外側で宣言されます。
static LANGUAGE: &str = "Rust";
const THRESHOLD: i32 = 10;

fn is_big(n: i32) -> bool {
    // 何らかの関数で定数にアクセスする
    n > THRESHOLD
}

fn main() {
    let n = 16;

    // メインスレッドで定数にアクセスする
    println!("This is {}", LANGUAGE);
    println!("The threshold is {}", THRESHOLD);
    println!("{} is {}", n, if is_big(n) { "big" } else { "small" });

    // エラー!`const` は変更できません。
    THRESHOLD = 5;
    // FIXME ^ この行をコメントアウトしてください
}

関連項目:

The const/static RFC, 'static ライフタイム