TryFrom/TryInto

ある型から別の型への、失敗する可能性がある変換。

導出可能: ❌

// Copyright 2025 Google LLC
// SPDX-License-Identifier: Apache-2.0

#[derive(Debug)]
pub struct InvalidNumber;

#[derive(Debug)]
pub struct DivisibleByTwo(usize);

impl TryFrom<usize> for DivisibleByTwo {
    type Error = InvalidNumber;

    fn try_from(value: usize) -> Result<Self, InvalidNumber> {
        if value.rem_euclid(2) == 0 {
            Ok(DivisibleByTwo(value))
        } else {
            Err(InvalidNumber)
        }
    }
}

fn main() {
    let success: Result<DivisibleByTwo, _> = 4.try_into();
    dbg!(success);
    let fail: Result<DivisibleByTwo, _> = 5.try_into();
    dbg!(fail);
}
  • 失敗する可能性のある変換を提供し、結果型を返します。

  • From/Into と同様に、TryInto ではなく 型に対して TryFrom を実装することを推奨します。

  • 実装では、Result のエラー型を指定できます。