Sub topic 2
to_string() for free
Assume you know structs, traits, Result, and basic formatting with println!. Rust’s Display trait defines user-facing text. When a type implements Display, the standard library automatically provides to_string() through a blanket implementation.
use std::{fmt, num::ParseIntError};
struct Price(f64);
impl fmt::Display for Price {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let precision = f.precision().unwrap_or(2);
let text = format!("{:.*}", precision, self.0);
write!(f, "{:>width$}", text, width = f.width().unwrap_or(0))
}
}
#[derive(Debug)]
enum PortError {
Parse(ParseIntError),
OutOfRange(i64),
}
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Parse(error) => write!(f, "not a number: {error}"),
Self::OutOfRange(port) => write!(f, "port {port} is out of range"),
}
}
}
impl From<ParseIntError> for PortError {
fn from(error: ParseIntError) -> Self {
Self::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))
}
struct Celsius(f64);
struct Fahrenheit(f64);
impl From<Celsius> for Fahrenheit {
fn from(value: Celsius) -> Self {
Self(value.0 * 9.0 / 5.0 + 32.0)
}
}
fn main() {
let price = Price(12.5);
println!("{}", price);
println!("{:>10.1}", price);
println!("text: {}", price.to_string());
println!("error: {}", parse_port("abc").unwrap_err());
let temperature = Fahrenheit::from(Celsius(100.0));
println!("{} F", temperature.0);
let temperature: Fahrenheit = Celsius(0.0).into();
println!("{} F", temperature.0);
}The width specifies a minimum field width. The precision controls digits after the decimal point in this implementation. A formatter option is meaningful only when your Display implementation reads and applies it.
Display is especially useful for error types. It should explain what went wrong in language suitable for a user or log reader. Debug can preserve structured diagnostic details, while Display provides the normal message.
From and Into
Implement From<Source> for Target when the conversion is clear and cannot fail. Rust then supplies Into<Target> automatically. Prefer implementing From; callers can use either Target::from(value) or value.into().
The ? operator also uses From. In parse_port, a ParseIntError becomes PortError automatically because of the From implementation. TryFrom is the related trait for conversions that can fail and need to return an error.
Exercise
Which trait should you implement to make value.to_string() work?
Show answer
Implement std::fmt::Display for the type.