Sub topic 3
From and the `?` Operator
Assume you know structs, enums, traits, ownership, Result, and match. This chapter connects conversions, error propagation, and default values.
From and the `?` operator
From<T> for U defines an infallible conversion from T to U. Rust then provides .into() in the opposite direction:
struct Celsius(f64);
struct Fahrenheit(f64);
impl From<Celsius> for Fahrenheit {
fn from(c: Celsius) -> Self {
Fahrenheit(c.0 * 9.0 / 5.0 + 32.0)
}
}
fn main() {
let boiling = Celsius(100.0);
let temperature: Fahrenheit = boiling.into();
println!("{}", temperature.0);
}? also uses From. If a function returns Result<T, AppError>, an expression such as value.parse()? converts the parser's error into AppError when From<ParseError> for AppError exists.
use std::num::ParseIntError;
#[derive(Debug)]
enum PortError {
Parse(ParseIntError),
OutOfRange(i64),
}
impl From<ParseIntError> for PortError {
fn from(error: ParseIntError) -> Self {
PortError::Parse(error)
}
}
fn parse_port(text: &str) -> Result<u16, PortError> {
let number: i64 = text.trim().parse()?;
u16::try_from(number).map_err(|_| PortError::OutOfRange(number))
}
fn main() {
println!("{:?}", parse_port("8080"));
println!("{:?}", parse_port("abc"));
}TryFrom when a conversion can fail
Use TryFrom<T> when some input values cannot be converted. It returns Result<U, Error>. The u16::try_from call above rejects negative numbers and values greater than 65_535.
Default values
Default supplies a conventional initial value. Derive it when field defaults are appropriate:
#[derive(Debug, Default)]
struct Settings {
retries: u32,
verbose: bool,
}For enums, mark one variant with #[default]:
#[derive(Debug, Default)]
enum Mode {
#[default]
Normal,
Fast,
}Use ..Default::default() to override selected fields:
let settings = Settings {
retries: 3,
..Default::default()
};Choosing and combining traits
- Use
Fromfor guaranteed conversions andTryFromfor fallible conversions. - Implement
Displayfor user-facing text andDebugfor diagnostic output. - Derive
Defaultwhen zero-like values are safe. Implement it manually when the type needs meaningful values. - Combining
From,Display, andDebugmakes custom errors work naturally with?, logs, and user messages.
Exercise
Which trait should convert an i64 to u16 when values outside the u16 range are possible?
Show answer
Use TryFrom<i64> because the conversion can fail.