Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Core Traits

The TryFrom and TryInto traits

Reference for the Rust TryFrom and TryInto traits: checked integer narrowing, validating constructors, the Error type, Infallible and use with the ? operator.

TryFrom<T> is the conversion trait for cases that can fail. Its method try_from returns a Result<Self, Self::Error>. TryInto<U> is the mirror image, value.try_into(), and you get it for free when you implement TryFrom.

The standard library uses it for checked integer narrowing (u8::try_from(300_i32) is an error instead of silently wrapping like as), for turning slices into arrays and for char::try_from(u32). You implement it for validating constructors: a type whose invariant must hold, built from a raw value.

Rust
let small = u8::try_from(200_i32);   // Ok(200)
let big: Result<u8, _> = 300_i32.try_into(); // Err(..)

Try it

Rust Checked integer and slice conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust A validating constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub trait TryFrom<T>: Sized {
    type Error;
    fn try_from(value: T) -> Result<Self, Self::Error>;
}

pub trait TryInto<T>: Sized {
    type Error;
    fn try_into(self) -> Result<T, Self::Error>;
}
Name Description
value / self The input, taken by value.
Error The error type you choose. For integers it is TryFromIntError; for char it is CharTryFromError; for slices to arrays it is TryFromSliceError.

Returns: Ok with the converted value, or Err explaining why the input was rejected.

Usage notes

  • Implement TryFrom, get TryInto. Like From and Into, a blanket impl derives TryInto for you.
  • Infallible conversions: every From impl also gives a TryFrom whose error is std::convert::Infallible, an uninhabitable type. That keeps generic code with T: TryFrom<U> working for conversions that never fail.
  • Prefer it to as for narrowing. as truncates silently (300_i32 as u8 is 44); try_from tells you. Use as only when wrapping is the goal.
  • The prelude includes TryFrom and TryInto since the 2021 edition; older editions need use std::convert::TryFrom;. The use above is harmless in edition 2024.
  • Collecting Results: iter.map(T::try_from).collect::<Result<Vec<_>, _>>() stops at the first error, as parse_all shows.
  • With ?: return the conversion error type from your function, or convert it using From so ? works.
  • Annotate the target. x.try_into() needs to know the target type, from a let annotation, a function parameter or the turbofish on try_from.
  • Not parsing. Turning text into a value is FromStr, not TryFrom<&str>, though you can provide both.
  • Error types should implement Display and Error so callers can print and box them. See std::error::Error.