Sub topic 17
Choosing and combining the traits
This chapter assumes you know how impl Trait for Type works, how println! format strings behave, and how Result and ? are used. Here you will pick the right trait for each job and see all four traits working in one small program.
Match the trait to the job
Each trait answers a different question. Start from what you need, then pick the trait.
| You need to... | Use | Derive or write by hand? |
|---|---|---|
| Inspect a value while debugging or in logs | `Debug` | Derive. Write by hand to hide fields such as passwords. |
| Show a value to an end user | `Display` | Always by hand. There is no derive. |
| Convert one type into another, and the conversion cannot fail | `From` | By hand. Call it with `.into()`. |
| Convert when the input might be invalid | `TryFrom` | By hand. |
| Provide a standard starting value | `Default` | Derive if every field's default is fine. Otherwise by hand. |
The traits working together
The traits depend on each other in practice. Error types need Debug and Display. From lets ? turn a library error into your error. Default with ..Default::default() sets up a value that only needs a few fields. Into makes constructors accept several input types.
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
BadNumber(ParseIntError),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::BadNumber(e) => write!(f, "retries is not a number: {}", e),
}
}
}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::BadNumber(e)
}
}
#[derive(Debug)]
struct Config {
name: String,
retries: u32,
verbose: bool,
}
impl Default for Config {
fn default() -> Self {
Config {
name: "app".to_string(),
retries: 3,
verbose: false,
}
}
}
impl fmt::Display for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} (retries: {})", self.name, self.retries)
}
}
impl Config {
fn named(name: impl Into<String>) -> Config {
Config {
name: name.into(),
..Default::default()
}
}
}
fn with_retries(text: &str) -> Result<Config, ConfigError> {
let retries: u32 = text.trim().parse()?;
Ok(Config {
retries,
..Default::default()
})
}
fn main() {
println!("{}", Config::named("worker"));
match with_retries("5") {
Ok(c) => {
println!("{}", c);
println!("{:?}", c);
}
Err(e) => println!("error: {}", e),
}
if let Err(e) = with_retries("many") {
println!("error: {}", e);
println!("{:?}", e);
}
}Here is what each trait does in this program:
Debugis derived on both types, so{:?}works andConfigErrormeets the usual expectation for error types.DisplayonConfigErrorgives the readable message.DisplayonConfiggives the user-facing line.From<ParseIntError>lets?convert the parse failure without amap_errcall.Defaultis written by hand becausenameshould be"app", not an empty string...Default::default()then fills in the fields you did not set.impl Into<String>lets callers pass a&stror aString.
Rules of thumb
- Derive first. Switch to a manual implementation only when the derived output or values are wrong for your type.
- Implement
From, notInto. You getIntofor free. - Use
Debugfor developers andDisplayfor users. Do not parseDebugoutput or show it to end users. - Prefer
TryFromoverFromwhen a conversion can panic or lose data.
Exercise
You are writing a Port(u16) type. Parsing a &str into a Port can fail, and a Port with no value given should be 8080. Which traits do you implement, and which of them can you derive?
Show answer
Implement TryFrom<&str> (or FromStr) for the fallible conversion, because From cannot report failure. Implement Default by hand, because the derived value would be 0, not 8080. Derive Debug for logging. Add Display by hand if users will see the port.