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.
let small = u8::try_from(200_i32); // Ok(200) let big: Result<u8, _> = 300_i32.try_into(); // Err(..)
Try it
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.
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
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, getTryInto. LikeFromandInto, a blanket impl derivesTryIntofor you. - Infallible conversions: every
Fromimpl also gives aTryFromwhose error isstd::convert::Infallible, an uninhabitable type. That keeps generic code withT: TryFrom<U>working for conversions that never fail. - Prefer it to
asfor narrowing.astruncates silently (300_i32 as u8is44);try_fromtells you. Useasonly when wrapping is the goal. - The prelude includes
TryFromandTryIntosince the 2021 edition; older editions needuse std::convert::TryFrom;. Theuseabove is harmless in edition 2024. - Collecting
Results:iter.map(T::try_from).collect::<Result<Vec<_>, _>>()stops at the first error, asparse_allshows. - With
?: return the conversion error type from your function, or convert it usingFromso?works. - Annotate the target.
x.try_into()needs to know the target type, from aletannotation, a function parameter or the turbofish ontry_from. - Not parsing. Turning text into a value is
FromStr, notTryFrom<&str>, though you can provide both. - Error types should implement
DisplayandErrorso callers can print and box them. Seestd::error::Error.