liveBook · Manning

TryFrom

As explained in Learn Rust in a Month of Lunches

TryFrom is a Rust trait for fallible conversion between types that may fail for some input values.

TryFrom is a Rust trait for conversions that might fail. Its try_from method returns a Result, so successful values become Ok and rejected inputs become Err. section 20.2 section 22.4

Use TryFrom when the input type can contain values that the destination type cannot accept:

  • Convert a u32 into a char only when the number represents a valid Unicode character. section 20.2
  • Validate data while constructing a type, such as accepting strings only up to a chosen character length. section 22.4
  • Use From when conversion cannot fail; Rust then supplies Into, and an Into implementation also supplies TryFrom with an infallible result. section 17.6

Rejecting an overlong string

An implementation of TryFrom<&str> for SmallStringHolder counts characters, returns Ok(Self(value.to_string())) for strings of five characters or fewer, and returns Err("Must be no longer than 5") otherwise. Calling SmallStringHolder::try_from("Hello") succeeds, while calling it with "Hello there" fails. section 22.4

#[derive(Debug)]
struct SmallStringHolder(String);
#[derive(Debug)]
struct MediumStringHolder(String);
#[derive(Debug)]
struct LargeStringHolder(String);
 
impl TryFrom<&str> for SmallStringHolder {
    type Error = &'static str;
 
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        if value.chars().count() > 5 {
            Err("Must be no longer than 5")
        } else {
            Ok(Self(value.to_string()))
        }
    }
}
 
fn main() {
    println!("{:?}", SmallStringHolder::try_from("Hello"));
    println!("{:?}", SmallStringHolder::try_from("Hello there"));
}

Inspect a complete TryFrom implementation with an associated error type, character-count validation, and successful or failed output. section 22.4

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains the Result-based trait contract through numeric, custom-type, blanket-implementation, and macro examples.
Examples
Uses u32-to-char conversion, length-limited string holders, error propagation, and generated implementations.
What it assumes
Assumes basic Rust types and traits while teaching fallible conversion through progressively concrete examples.
What you can do after
Builds fallible conversions that return meaningful success or error values and applies them through try_from.
How it connects
Connects TryFrom with From, Into, Result, Unicode characters, macros, and const generics.

Also explained in

Compare how 3 books explain TryFrom →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.