パターンマッチングを使った Rust の構造体の分解

RustRustBeginner
今すぐ練習

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

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

はじめに

この実験では、Rust での struct の分解について学びます。これにより、パターンマッチングを使って、構造体から個々のフィールドとその値を抽出することができます。

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/BasicConceptsGroup(["Basic Concepts"]) rust(("Rust")) -.-> rust/DataTypesGroup(["Data Types"]) rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust(("Rust")) -.-> rust/MemorySafetyandManagementGroup(["Memory Safety and Management"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("Variable Declarations") rust/DataTypesGroup -.-> rust/integer_types("Integer Types") rust/DataTypesGroup -.-> rust/string_type("String Type") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("Lifetime Specifiers") subgraph Lab Skills rust/variable_declarations -.-> lab-99314{{"パターンマッチングを使った Rust の構造体の分解"}} rust/integer_types -.-> lab-99314{{"パターンマッチングを使った Rust の構造体の分解"}} rust/string_type -.-> lab-99314{{"パターンマッチングを使った Rust の構造体の分解"}} rust/function_syntax -.-> lab-99314{{"パターンマッチングを使った Rust の構造体の分解"}} rust/expressions_statements -.-> lab-99314{{"パターンマッチングを使った Rust の構造体の分解"}} rust/lifetime_specifiers -.-> lab-99314{{"パターンマッチングを使った Rust の構造体の分解"}} end

構造体

同様に、構造体 を以下のように分解することができます。

fn main() {
    struct Foo {
        x: (u32, u32),
        y: u32,
    }

    // 構造体の値を変更して何が起こるか見てみてください
    let foo = Foo { x: (1, 2), y: 3 };

    match foo {
        Foo { x: (1, b), y } => println!("x の最初の値は 1、b = {}, y = {} ", b, y),

        // 構造体を分解して変数をリネームすることができます
        // 順序は重要ではありません
        Foo { y: 2, x: i } => println!("y は 2、i = {:?}", i),

        // また、一部の変数を無視することもできます。
        Foo { y,.. } => println!("y = {}, x については気にしません", y),
        // これはエラーになります:パターンにフィールド `x` が含まれていません
        //Foo { y } => println!("y = {}", y),
    }

    let faa = Foo { x: (1, 2), y: 3 };

    // 構造体を分解するには match ブロックは必要ありません:
    let Foo { x : x0, y: y0 } = faa;
    println!("外側:x0 = {x0:?}, y0 = {y0}");
}

まとめ

おめでとうございます!あなたは構造体の実験を完了しました。あなたのスキルを向上させるために、LabEx でさらに多くの実験を行って練習してください。