Sub topic 17
Choosing and combining the traits
This chapter assumes you have read the earlier chapters on Debug, Display, From/Into, TryFrom, and Default. It also assumes Rust edition 2021, where TryFrom and TryInto are in the prelude. Here you will decide which trait fits a job and see all of them working in one small program.
The traits side by side
Each trait answers a different question about a type.
| Trait | Question it answers | Derive? | Typical caller |
|---|---|---|---|
| `Debug` | What does this value look like to a developer? | Usually | `{:?}`, `{:#?}`, `dbg!`, `unwrap` failures |
| `Display` | How should this value read to a user? | Never | `{}`, `to_string()` |
| `From<T>` | How do I build `Self` from a `T` that cannot fail? | No | `Self::from(t)`, `t.into()`, `?` |
| `TryFrom<T>` | How do I build `Self` from a `T` that might fail? | No | `Self::try_from(t)`, `t.try_into()` |
| `Default` | What is a sensible starting value? | Often | `Default::default()`, `..Default::default()` |
Display cannot be derived because the compiler has no way to know what user-facing text you want.
A decision path
Start from what you need the type to do, not from the trait name.
Derive or write by hand
Derive when the generated code does what you would have written.
- Derive
Debugon almost every type. The cost is small, and it letsunwrap,assert_eq!, anddbg!show your values. Every field type must also implementDebug. - Write
Debugby hand when a field is secret, huge, or meaningless to print. Usedebug_structso the output keeps the standard shape. - Derive
Defaultonly if every field's default is a value you would choose on purpose. A derived default for aport: u16is0, which is rarely a real port. For enums, mark the default variant with#[default]. - Always write
DisplayandFromby hand. ForDisplay, decide on the text. ForFrom, decide how the data maps across.
Rules that prevent common errors
- Implement
From, notInto. The standard library suppliesimpl<T, U: From<T>> Into<U> for T, so everyFromgives you.into(). ImplementingIntodirectly losesFromand the?conversion. - Implement
Display, notToString.to_string()comes from a blanket implementation overDisplay. A manualToStringwould conflict with it. - Use
Fromonly for conversions that cannot fail. If you would be tempted tounwrapor panic inside it, useTryFrom. - Do not implement both
From<A> for BandTryFrom<A> for B.Fromalready givesTryFrom<A> for Bthrough a blanket implementation withError = Infallible, so the second implementation is rejected as conflicting. - Error types need both
DebugandDisplay.std::error::Errorrequires both.Debugis for logs andunwrap, andDisplayis for the message a user reads. - Never parse
Debugoutput. Its format is not stable across compiler versions. If a value needs a stable text form, give it aDisplayimplementation (andFromStrif you also need to parse it). - Do not use
Defaultto hide an invalid state. If an empty or zero value would break the type's rules, provide a constructor that returnsResultinstead.
One program, all four traits
The next program is a small server configuration. It uses each trait for the job that suits it.
Portwraps au16and usesTryFrom<i64>to reject out-of-range numbers.ConfigErrorhasDebug(derived),Display(manual), andFrom<ParseIntError>, so?works.Serverhas a manualDebugthat hides the token and a manualDefault.with_hostacceptsimpl Into<String>, so callers can pass&strorString.
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
BadNumber(ParseIntError),
BadPort(i64),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::BadNumber(e) => write!(f, "not a number: {}", e),
ConfigError::BadPort(n) => write!(f, "port {} is out of range", n),
}
}
}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::BadNumber(e)
}
}
#[derive(Debug, Clone, Copy)]
struct Port(u16);
impl TryFrom<i64> for Port {
type Error = ConfigError;
fn try_from(n: i64) -> Result<Self, Self::Error> {
u16::try_from(n)
.map(Port)
.map_err(|_| ConfigError::BadPort(n))
}
}
impl fmt::Display for Port {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, ":{}", self.0)
}
}
struct Server {
host: String,
port: Port,
token: String,
}
impl Default for Server {
fn default() -> Self {
Server {
host: "localhost".to_string(),
port: Port(8080),
token: String::new(),
}
}
}
impl fmt::Debug for Server {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Server")
.field("host", &self.host)
.field("port", &self.port)
.field("token", &"<hidden>")
.finish()
}
}
impl fmt::Display for Server {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}{}", self.host, self.port)
}
}
impl Server {
fn with_host(mut self, host: impl Into<String>) -> Self {
self.host = host.into();
self
}
}
fn parse_port(s: &str) -> Result<Port, ConfigError> {
let n: i64 = s.trim().parse()?;
Port::try_from(n)
}
fn main() {
let server = Server {
port: Port(9000),
token: "s3cret".to_string(),
..Default::default()
}
.with_host("example.org");
println!("{}", server);
println!("{:?}", server);
for input in ["8080", "abc", "70000"] {
match parse_port(input) {
Ok(p) => println!("ok {}", p),
Err(e) => println!("error: {}", e),
}
}
}Running it prints:
example.org:9000
Server { host: "example.org", port: Port(9000), token: "<hidden>" }
ok :8080
error: not a number: invalid digit found in string
error: port 70000 is out of rangeHere is how each trait contributes.
Defaultand struct update syntax...Default::default()fills in only the fields the caller left out. BecauseServerhas aDrop-free layout, moving the remaining fields out of the temporary default value is allowed.Intoin an argument.with_host("example.org")works because&strimplementsInto<String>throughFrom<&str> for String.Fromand?. The?inparse_portcallsConfigError::fromon theParseIntError. Nomap_erris needed.TryFromfor validation. The range check lives in one place. Any code that needs aPortfrom ani64goes through it, andn.try_into()also works.- Two print styles.
Displaygives the short address a user would read.Debugshows the structure for a developer and omits the token.
What to check in a review
When you review a type that implements these traits, ask these questions.
- Does
Debugleak anything that should not appear in logs? - Does
Displayproduce a complete message that makes sense without surrounding context? Error messages usually start lowercase and have no trailing period. - Does any
Fromimplementation panic, truncate, or lose information? If so, switch toTryFrom. - Does a derived
Defaultproduce a value the type's own rules accept? - Is each conversion defined once, on the target type, so there is one place to read it?
Exercises
Exercise
A type Level(u8) must only hold 1 to 5. A teammate wrote impl From<u8> for Level that clamps any input into that range. What is the problem, and what should the conversion be?
Show answer
From signals that a conversion cannot fail and loses nothing, but clamping silently changes the input, so a caller who passes 200 gets Level(5) without any warning. Use impl TryFrom<u8> for Level that returns an error for values outside 1 to 5. Callers then handle the failure with Level::try_from(n) or n.try_into().
Exercise
You have struct Job { name: String, retries: u32, secret: String }. You derive Debug and Default, then write println!("{:?}", Job::default()) in a log statement. Name one reason to change the derives and what you would change.
Show answer
The derived Debug prints secret in plain text whenever a real job is logged, so replace it with a manual Debug that uses debug_struct and writes "<hidden>" for secret. You could also revisit Default to check that an empty name and zero retries are valid starting values for a job.