Rust By Example 第6章 変換 日本語訳

Rust By Example 第6章だけ日本語訳がなかったので翻訳しました。プルリクを投げるほど自分の翻訳に自信がなかったのでブログに載せます。


6.1 FromInto

FromトレイトとIntoトレイトは本質的に関連しています。and this is actually part of its implementation. もしも型Bから型Aへ変換できるなら、普通、型Aから型Bへ変換することもできるはずです。

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::From;

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

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

fn main() {
    let int = 5;
    // Try removing the type declaration
    // 型宣言を除去してみよう
    let num: Number = int.into();
    println!("My number is {:?}", num);
}

Copylight (c) 2021 orient-ex
Released under the MIT License
https://opensource.org/licenses/MIT