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


