Sub topic 13
TryFrom when a conversion can fail
This chapter assumes you know From and Into from the previous chapters, how impl Trait for Type works, and how Result and the ? operator behave. It also assumes you can write a small error type with Display.
Why From is not enough
From describes a conversion that always succeeds. Its signature, fn from(value: T) -> Self, has no way to report failure. Many real conversions can fail:
- A number may not fit in a smaller integer type.
- A number may fall outside the range a type allows, such as a percentage above 100.
- A byte may not match any variant of an enum.
You could panic inside from, but that hides a recoverable problem behind a crash. TryFrom solves this by returning a Result.
The trait definition
TryFrom lives in std::convert. Its definition is:
pub trait TryFrom<T>: Sized {
type Error;
fn try_from(value: T) -> Result<Self, Self::Error>;
}There are two differences from From:
- The return type is
Result<Self, Self::Error>. - The trait has an associated type,
Error. Each implementation chooses its own error type.
TryFrom and TryInto are in the prelude from Rust 2021 onward. In older editions you need use std::convert::TryFrom; or use std::convert::TryInto;.
Implementing TryFrom for a validated type
The usual use is a type that guards an invariant. Percent holds a u8, but only values from 0 to 100 are allowed.
use std::fmt;
#[derive(Debug, PartialEq)]
struct Percent(u8);
#[derive(Debug, PartialEq)]
struct PercentError(i32);
impl fmt::Display for PercentError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} is not between 0 and 100", self.0)
}
}
impl TryFrom<i32> for Percent {
type Error = PercentError;
fn try_from(value: i32) -> Result<Self, Self::Error> {
if (0..=100).contains(&value) {
Ok(Percent(value as u8))
} else {
Err(PercentError(value))
}
}
}
fn main() {
println!("{:?}", Percent::try_from(42_i32));
println!("{:?}", Percent::try_from(250_i32));
let n: i32 = 77;
let r: Result<Percent, _> = n.try_into();
println!("{:?}", r);
if let Err(e) = Percent::try_from(-5_i32) {
println!("error: {}", e);
}
}The as u8 cast is safe here because the range check has already run. The error type carries the rejected value, which makes the message useful to the caller.
TryInto: calling from the other side
As with From and Into, you implement only TryFrom. The standard library supplies TryInto through a blanket implementation:
impl<T, U> TryInto<U> for T
where
U: TryFrom<T>,
{
type Error = U::Error;
fn try_into(self) -> Result<U, U::Error> { /* calls U::try_from(self) */ }
}In the example above, n.try_into() works because Percent: TryFrom<i32>. The compiler usually cannot guess the target type, so you must name it with a type annotation, a turbofish, or a function parameter type.
In function signatures, prefer TryFrom as the bound only when you need to name the types involved. A bound like T: TryInto<u8> is the common way to accept "anything convertible to a u8, possibly failing".
Fallible conversions in the standard library
The integer types use TryFrom for conversions that might lose information. Lossless widening uses From.
fn main() {
let big: i32 = 300;
match u8::try_from(big) {
Ok(v) => println!("fits: {}", v),
Err(e) => println!("error: {}", e),
}
println!("{:?}", u8::try_from(200_i32));
println!("{}", u32::try_from(-1_i32).is_err());
// The `as` cast silently wraps instead of reporting a problem.
println!("{}", 300_i32 as u8);
}This prints:
error: out of range integral type conversion attempted
Ok(200)
true
44The last line shows why try_from is worth using. 300_i32 as u8 produces 44 with no warning, which is rarely what you want. u8::try_from(300_i32) returns Err(TryFromIntError), and you must decide what to do with it.
Combining TryFrom with the ? operator
TryFromIntError is an ordinary error type, so you can convert it into your own error with From and let ? do the work. This extends the PortError pattern from the earlier chapters.
use std::fmt;
use std::num::{ParseIntError, TryFromIntError};
#[derive(Debug)]
enum PortError {
Parse(ParseIntError),
Range(TryFromIntError),
}
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PortError::Parse(e) => write!(f, "not a number: {}", e),
PortError::Range(e) => write!(f, "port out of range: {}", e),
}
}
}
impl From<ParseIntError> for PortError {
fn from(e: ParseIntError) -> Self {
PortError::Parse(e)
}
}
impl From<TryFromIntError> for PortError {
fn from(e: TryFromIntError) -> Self {
PortError::Range(e)
}
}
fn parse_port(s: &str) -> Result<u16, PortError> {
let n: i64 = s.trim().parse()?;
let port = u16::try_from(n)?;
Ok(port)
}
fn main() {
println!("{:?}", parse_port("8080"));
for input in ["abc", "70000"] {
if let Err(e) = parse_port(input) {
println!("error: {}", e);
}
}
}Each ? calls PortError::from on its own error type. Compare this with the earlier version, which used map_err for the range check. Once From<TryFromIntError> exists, the map_err call is no longer needed. The trade-off is that the error no longer carries the rejected number, so add that field yourself if the message needs it.
The relationship between From and TryFrom
The standard library has this blanket implementation:
impl<T, U> TryFrom<U> for T
where
U: Into<T>,
{
type Error = Infallible;
// ...
}Every infallible conversion is automatically a fallible one whose error can never occur. Infallible is an enum with no variants, so a value of that type cannot exist.
use std::convert::Infallible;
fn main() {
let r: Result<i64, Infallible> = i64::try_from(5_i32);
println!("{:?}", r);
}This blanket implementation has a consequence you will hit as a compile error. If you write both impl From<i32> for Percent and impl TryFrom<i32> for Percent, the two conflict, because From already provides a TryFrom<i32> implementation. For a given source and target pair, choose one.
Edge cases and gotchas
- Platform-dependent sizes.
usizeandisizedepend on the target. A conversion such asu32::try_from(some_usize)always compiles but may succeed or fail depending on the value. Never assume ausizefits in 32 bits. - Weak error types. Using
Stringor()asErrorcompiles, but callers cannot match on the failure or convert it with?into a typed error. Use a small struct or enum withDisplay, asPercentErrordoes. - Inference failures.
value.try_into()with no annotation gives a "type annotations needed" error. Name the target type. - Validation lives in one place. If the type's fields are private,
TryFrombecomes the only way to build it from raw data, so the invariant cannot be bypassed outside the module. - Borrowed sources. You can implement
TryFrom<&str>for parsing small enums, but if the conversion is really parsing text,FromStrand.parse()are the conventional choice.
Choosing between From, TryFrom, and a plain function
A named function is the better choice when the conversion needs extra input, such as a base for number parsing, or when several different conversions between the same pair of types would be confusing under one trait.
Exercise
A teammate writes both impl From<u8> for Level and impl TryFrom<u8> for Level. Why does this not compile, and what should they change?
Show answer
The standard library already provides TryFrom<u8> for Level (with Error = Infallible) for any type that implements From<u8>, so the second implementation conflicts with it. They should keep only one. If some u8 values are not valid levels, remove the From implementation and keep TryFrom with a real error type. If every u8 is a valid level, keep From and delete TryFrom.
Exercise
What does u8::try_from(-1_i32) return, and how does that differ from -1_i32 as u8?
Show answer
It returns Err(TryFromIntError), because -1 is outside the range 0 to 255. The cast -1_i32 as u8 produces 255 without any error, because as wraps the bits instead of checking the range.