From と Into

RustRustBeginner
今すぐ練習

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

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

はじめに

この実験では、Rust におけるFromIntoトレイトの概念を探ります。これらのトレイトは、異なる型間の変換に使用されます。これらのトレイトは本質的に関連付けられており、IntoFromの逆です。Fromトレイトは、型が別の型から自身を作成する方法を定義することを可能にし、型間の変換を容易にします。Intoトレイトは、必要に応じて自動的にFromの実装を呼び出します。両方のトレイトはカスタム型に対して実装でき、型変換に柔軟性を提供します。

注: 実験でファイル名が指定されていない場合は、好きなファイル名を使用できます。たとえば、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/DataStructuresandEnumsGroup(["Data Structures and Enums"]) rust(("Rust")) -.-> rust/AdvancedTopicsGroup(["Advanced Topics"]) 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/DataStructuresandEnumsGroup -.-> rust/method_syntax("Method Syntax") rust/AdvancedTopicsGroup -.-> rust/traits("Traits") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("Traits for Operator Overloading") subgraph Lab Skills rust/variable_declarations -.-> lab-99299{{"From と Into"}} rust/integer_types -.-> lab-99299{{"From と Into"}} rust/string_type -.-> lab-99299{{"From と Into"}} rust/function_syntax -.-> lab-99299{{"From と Into"}} rust/expressions_statements -.-> lab-99299{{"From と Into"}} rust/method_syntax -.-> lab-99299{{"From と Into"}} rust/traits -.-> lab-99299{{"From と Into"}} rust/operator_overloading -.-> lab-99299{{"From と Into"}} end

FromInto

FromInto トレイトは本質的に関連付けられており、これは実際にその実装の一部です。型 A を型 B から変換できる場合、型 B を型 A に変換できるはずだと考えるのは簡単です。

From

From トレイトは、型が別の型から自身を作成する方法を定義することを可能にし、いくつかの型間の変換に非常に単純なメカニズムを提供します。標準ライブラリ内には、基本型と一般的な型の変換に対するこのトレイトの多数の実装があります。

たとえば、strString に簡単に変換できます。

let my_str = "hello";
let my_string = String::from(my_str);

独自の型の変換を定義する場合も同様にできます。

use std::convert::From;

#[derive(Debug)]
struct Number {
    value: i32,
}

impl From<i32> for Number {
    fn from(item: i32) -> Self {
        Number { value: item }
    }
}

fn main() {
    let num = Number::from(30);
    println!("My number is {:?}", num);
}

Into

Into トレイトは、単に From トレイトの逆です。つまり、型に対して From トレイトを実装している場合、Into は必要に応じてそれを呼び出します。

Into トレイトを使用する場合、通常は変換先の型を指定する必要があります。なぜなら、コンパイラはほとんどの場合これを判断できないからです。ただし、この機能を無料で得られることを考えると、これは小さなトレードオフにすぎません。

use std::convert::Into;

#[derive(Debug)]
struct Number {
    value: i32,
}

impl Into<Number> for i32 {
    fn into(self) -> Number {
        Number { value: self }
    }
}

fn main() {
    let int = 5;
    // 型注釈を削除してみてください
    let num: Number = int.into();
    println!("My number is {:?}", num);
}

まとめ

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