typestar

TryFrom for checked conversions in Rust

TryFrom is From for conversions that may fail, and it gives you try_into.

use std::convert::TryFrom;

struct Stars(u8);

impl TryFrom<i64> for Stars {
    type Error = String;

    fn try_from(value: i64) -> Result<Self, Self::Error> {
        match value {
            0..=3 => Ok(Stars(value as u8)),
            other => Err(format!("{other} is not 0 to 3")),
        }
    }
}

fn main() {
    let ok = Stars::try_from(3).map(|s| s.0);
    println!("{:?}", ok);

    let bad: Result<Stars, String> = 9_i64.try_into();
    println!("{}", bad.err().unwrap());
}

How it works

  1. Implementing TryFrom provides try_into for free.
  2. The associated Error type names the failure.
  3. Validation lives in one place instead of every call site.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
421
Tokens
146
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 83 seconds.

Type this snippet

Step 5 of 5 in Your own error types, step 12 of 15 in Error handling.

← Previous Next →