Implement FromStr For Custom Parsing
Implement FromStr so a custom type plugs into str.parse, returning a typed error instead of a generic message on bad input.
Code
use std::fmt;
use std::str::FromStr;
#[derive(Debug)]
struct Port(u16);
#[derive(Debug)]
enum PortError {
Empty,
NotNumeric,
OutOfRange(u64),
}
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PortError::Empty => write!(f, "port is empty"),
PortError::NotNumeric => write!(f, "port is not a number"),
PortError::OutOfRange(v) => write!(f, "port {v} exceeds u16 range"),
}
}
}
impl FromStr for Port {
type Err = PortError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.trim().is_empty() {
return Err(PortError::Empty);
}
let n: u64 = s.trim().parse().map_err(|_| PortError::NotNumeric)?;
if n > u16::MAX as u64 {
return Err(PortError::OutOfRange(n));
}
Ok(Port(n as u16))
}
}
fn main() {
for input in ["8080", " 443 ", "", "99999", "http"] {
match input.parse::<Port>() {
Ok(port) => println!("{input:?} -> {:?}", port),
Err(e) => println!("{input:?} -> error: {e}"),
}
}
}How it works
PortError declares three variants that name the real failure modes: Empty for blank input, NotNumeric when s.trim().parse::<u64>() fails, and OutOfRange(u64) carrying the offending value when it exceeds u16::MAX. impl fmt::Display for PortError renders each variant, so println!("{input:?} -> error: {e}") in main prints a readable message per failed input.
impl FromStr for Port sets type Err = PortError, which is what lets input.parse::<Port>() return Result<Port, PortError> instead of a generic string error. Inside from_str, the ? after parse() short-circuits into the mapped variant, and the for input in ["8080", " 443 ", "", "99999", "http"] loop in main exercises all five outcomes — " 443 " trims clean, 99999 lands in OutOfRange, "http" in NotNumeric.
Points of care
- The trait method signature is fixed by
FromStr— only theErrassociated type is yours to choose, so pick variants that say why parsing failed. - Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch. Ok(Port(n as u16))is safe only because then > u16::MAX as u64guard runs first — reorder those two statements and the cast silently truncates.
Putting it to use
Entry signature: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
Core lines
return Err(PortError::OutOfRange(n));
return Err(PortError::Empty);
let n: u64 = s.trim().parse().map_err(|_| PortError::NotNumeric)?;
return Err(PortError::OutOfRange(n));
return Err(PortError::Empty);
let n: u64 = s.trim().parse().map_err(|_| PortError::NotNumeric)?;
Interactive Tools for This Topic
FAQ
- How are errors reported?
- Through `Result` values propagated with the `?` operator. Nothing panics inside the snippet; the caller decides how to handle each failure.
- How do you run Implement FromStr For Custom Parsing?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.