Sub topic 13
TryFrom when a conversion can fail
This chapter assumes you know how From and Into work, how Result and ? behave, and how to implement Display for an error type.
Why From is not enough
From promises that a conversion always works. Many conversions can't make that promise. A negative i64 doesn't fit in a u16, and 0 is not a usable port number. Putting a panic or a silent fallback inside from hides the problem from the caller.
TryFrom is the fallible version. It returns a Result, so the caller decides what to do when the conversion fails.
pub trait TryFrom<T>: Sized {
type Error;
fn try_from(value: T) -> Result<Self, Self::Error>;
}The associated type Error names the failure type. Each implementation picks its own.
Implementing TryFrom
This example converts an i64 into a validated Port. The error type carries the rejected value and implements Display, as described in the error-types chapter.
use std::convert::TryFrom;
use std::fmt;
#[derive(Debug)]
struct Port(u16);
#[derive(Debug)]
struct PortError(i64);
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} is not a valid port", self.0)
}
}
impl TryFrom<i64> for Port {
type Error = PortError;
fn try_from(n: i64) -> Result<Self, Self::Error> {
if (1..=65535).contains(&n) {
Ok(Port(n as u16))
} else {
Err(PortError(n))
}
}
}
fn main() {
println!("{:?}", Port::try_from(8080_i64));
let result: Result<Port, PortError> = 0_i64.try_into();
match result {
Ok(p) => println!("port {}", p.0),
Err(e) => println!("error: {}", e),
}
}This prints Ok(Port(8080)) and then error: 0 is not a valid port. The use std::convert::TryFrom; line is only needed before Rust edition 2021. Later editions include the trait in the prelude.
TryInto comes for free
As Into follows from From, TryInto follows from TryFrom. Implement TryFrom<i64> for Port and you can call .try_into() on an i64. Write TryFrom, not TryInto. As with Into, the compiler usually needs a type annotation on the result so it knows the target type.
TryFrom in the standard library
The integer types use TryFrom for narrowing conversions:
fn main() {
println!("{:?}", u8::try_from(200_i32));
println!("{:?}", u8::try_from(300_i32));
println!("{:?}", i8::try_from(-1_i64));
}The first and third calls return Ok. The second returns Err(TryFromIntError(())). Prefer these over as, which silently truncates 300_i32 to 44.
Using it with the ? operator
If your function's error type implements From<PortError>, ? converts the failure automatically:
let port = Port::try_from(n)?;This ties the chapter back to From and ?. TryFrom produces the specific error, and From lifts it into your function's error type.
Choosing between them
| Situation | Trait |
|---|---|
| Conversion always succeeds | `From` |
| Conversion can reject the input | `TryFrom` |
| Calling from the source value's side | `Into` or `TryInto` |
Exercise
Implement TryFrom<&str> for Percent, where Percent(u8) accepts only values from 0 to 100. What should type Error be, and which two failures must try_from handle?
Show answer
Use a custom error enum, for example PercentError { NotANumber(ParseIntError), OutOfRange(i64) }, or String for a quick version. The two failures are text that doesn't parse as a number, and a number outside 0..=100. Parse with s.trim().parse::<i64>(), map the parse error into NotANumber (or add From<ParseIntError> and use ?), then return Err(OutOfRange(n)) if !(0..=100).contains(&n). Otherwise return Ok(Percent(n as u8)).