Rust の変数バインディング宣言

RustRustBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Rust プログラミング言語で変数バインディングを先に宣言し、後で初期化する例を見ます。

注: 実験でファイル名が指定されていない場合、好きなファイル名を使用できます。たとえば、main.rs を使用して、rustc main.rs &&./main でコンパイルして実行できます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/BasicConceptsGroup(["Basic Concepts"]) rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("Variable Declarations") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") subgraph Lab Skills rust/variable_declarations -.-> lab-99293{{"Rust の変数バインディング宣言"}} rust/function_syntax -.-> lab-99293{{"Rust の変数バインディング宣言"}} rust/expressions_statements -.-> lab-99293{{"Rust の変数バインディング宣言"}} end

先に宣言する

変数バインディングを先に宣言し、後で初期化することができます。ただし、この形式はほとんど使用されず、未初期化の変数が使用される可能性があるためです。

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);
}

コンパイラは未初期化の変数の使用を禁止します。これは未定義の動作につながるためです。

まとめ

おめでとうございます!「先に宣言する」実験を完了しました。技術力を向上させるために、LabEx でさらに多くの実験を行って練習してください。