Traits and error handling in Rust
A trait describes what a type can do. With generics, the compiler makes a fast copy of your code for each type. With a trait object (dyn), one copy of the code works with many types at run time. Errors are normal values of the Result type, and the question mark operator passes them up with very little code. Libraries return clear error types and do not panic; applications add context and decide what to do.
Author: bezzad
Contents
The problem: many rules, many failures
The checkout of our online shop must apply discounts. Marketing keeps adding new kinds: “10% off”, “free shipping over $50”, “buy two, get one free”. The checkout must not change every time a new rule arrives.
Checkout can also fail in many ways: the coupon code is unknown, the price file is broken, the payment is declined. None of these may crash the whole server. Each one must reach the right place with a clear message.
Rust has two tools for this: traits for “many types with the same behavior”, and the Result type for “this can fail”.
Traits: shared behavior
A trait is a list of methods that a type promises to have. It is close to an interface in Java or C#.
pub struct Cart {
pub subtotal_cents: u64,
pub shipping_cents: u64,
}
pub trait Discount {
fn name(&self) -> String;
fn amount_off(&self, cart: &Cart) -> u64;
// A default method: types get it for free and may override it.
fn applies_to(&self, cart: &Cart) -> bool {
self.amount_off(cart) > 0
}
}
pub struct PercentOff {
pub percent: u64,
}
pub struct FreeShippingOver {
pub limit_cents: u64,
}
impl Discount for PercentOff {
fn name(&self) -> String {
format!("{}% off", self.percent)
}
fn amount_off(&self, cart: &Cart) -> u64 {
cart.subtotal_cents * self.percent / 100
}
}
impl Discount for FreeShippingOver {
fn name(&self) -> String {
"free shipping".to_string()
}
fn amount_off(&self, cart: &Cart) -> u64 {
if cart.subtotal_cents >= self.limit_cents {
cart.shipping_cents
} else {
0
}
}
}
- The trait says what, each impl block says how.
- Default methods like applies_to are written once in the trait.
- You can implement your own traits for any type, and standard traits (like Display) for your own types. You cannot implement a foreign trait for a foreign type. This is called the orphan rule, and it stops two crates from fighting over the same impl.
Generics with trait bounds: static dispatch
A generic function works for any type that has the trait:
pub fn price_after<D: Discount>(cart: &Cart, discount: &D) -> u64 {
let full = cart.subtotal_cents + cart.shipping_cents;
full - discount.amount_off(cart)
}
// The same, shorter: "some type that implements Discount"
pub fn describe(discount: &impl Discount) -> String {
format!("Discount: {}", discount.name())
}
The compiler makes a separate copy of the function for each type you call it with. This is called monomorphization.
- Each copy knows the exact type, so calls are direct and can be inlined. This is as fast as hand-written code.
- The cost is compile time and binary size, because there are more copies.
- All types must be known at compile time. One call works with one type.
Trait objects: dynamic dispatch
The list of active discounts comes from the database at run time. It holds different types in one list. For this we need a trait object:
pub fn best_discount(
cart: &Cart,
discounts: &[Box<dyn Discount>],
) -> Option<String> {
discounts
.iter()
.filter(|d| d.applies_to(cart))
.max_by_key(|d| d.amount_off(cart))
.map(|d| d.name())
}
fn main() {
let cart = Cart { subtotal_cents: 6000, shipping_cents: 500 };
let discounts: Vec<Box<dyn Discount>> = vec![
Box::new(PercentOff { percent: 10 }),
Box::new(FreeShippingOver { limit_cents: 5000 }),
];
// prints Some("10% off")
println!("{:?}", best_discount(&cart, &discounts));
}
- A trait object is a fat pointer: one pointer to the data and one pointer to a vtable, a table with the addresses of the methods for that type.
- Each call looks up the method in the vtable. This is a small cost, and the compiler usually cannot inline it.
- There is only one copy of the code, and the list can hold any type that implements the trait, even types from other crates.
- The value lives behind a pointer, usually a Box, a reference or an Arc, because the size of the real type is not known.
Not every trait can be a trait object
To build a vtable, the compiler needs one fixed address for each method. So a trait is dyn compatible (the old name was “object safe”) only if its methods allow that. The two rules you meet most often:
- No generic methods. A generic method has a new copy for every type argument, so there is no single address for the vtable.
- No method that returns Self by value, because the size of Self is not known behind dyn.
If one method breaks a rule, you can keep the trait usable as dyn by adding a where clause that requires Self to be Sized to that method. That method is then simply not available on the trait object.
Which one to choose?
- Generics when the type is known at compile time and speed matters, for example a parser or a hot loop.
- A trait object when you need a list of mixed types, plugins, or types chosen by configuration at run time.
- An enum when the set of types is closed and all of them are in your crate. A match over an enum is fast, and the compiler checks that you handled every case.
Useful standard traits
Most types should derive a few standard traits:
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct OrderId(pub u64);
impl fmt::Display for OrderId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{}", self.0)
}
}
- Debug is for developers and logs. Display is for users, and you write it by hand.
- Clone, Copy, PartialEq, Eq and Hash let you copy, compare and use the type as a key in a HashMap.
- The From trait describes a conversion. The question mark operator uses it to convert errors, as we see below.
Errors are values: Result
In Rust, a function that can fail returns a Result. It is an enum with two variants: Ok with the value, or Err with the error.
#[derive(Debug)]
pub enum CouponError {
Unknown(String),
Expired(String),
}
pub fn find_coupon(code: &str) -> Result<PercentOff, CouponError> {
match code {
"WELCOME10" => Ok(PercentOff { percent: 10 }),
"SUMMER24" => Err(CouponError::Expired(code.to_string())),
_ => Err(CouponError::Unknown(code.to_string())),
}
}
- The error is in the type. The caller cannot forget it, because they must take the value out of the Result.
- There are no hidden exceptions. You see in the signature which functions can fail.
- A panic is different. It is for bugs, a broken rule that should never happen. A panic stops the current thread. Bad user input is not a bug, so it must be an Err, not a panic.
The question mark operator
Checking every Result with a match gets long. The question mark operator does it for you:
use std::fs;
use std::num::ParseIntError;
#[derive(Debug)]
pub enum ConfigError {
Io(std::io::Error),
BadNumber(ParseIntError),
}
impl From<std::io::Error> for ConfigError {
fn from(e: std::io::Error) -> Self {
ConfigError::Io(e)
}
}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::BadNumber(e)
}
}
pub fn read_shipping_limit(path: &str) -> Result<u64, ConfigError> {
// io::Error -> ConfigError
let text = fs::read_to_string(path)?;
// ParseIntError -> ConfigError
let cents = text.trim().parse::<u64>()?;
Ok(cents)
}
What the question mark does, step by step:
- If the value is Ok, it takes the value out and the code goes on.
- If the value is Err, it converts the error with the From trait into the error type of the function.
- Then it returns that error from the function right away.
The question mark also works with Option, inside a function that returns Option. It returns None early.
Library errors with thiserror
Writing the From impls and the Display impl by hand is boring. The thiserror crate generates them. It is the usual choice for libraries, where callers need to match on exact error cases:
use thiserror::Error;
#[derive(Debug, Error)]
pub enum PaymentError {
#[error("card was declined: {reason}")]
Declined { reason: String },
#[error("payment provider did not answer")]
Timeout,
#[error("could not read the provider response")]
BadResponse(#[from] serde_json::Error),
}
- The error attribute writes the Display text.
- The from attribute writes the From impl, so the question mark converts the error. It also marks the inner error as the source, so the full chain of causes is kept.
- Callers can match on Declined and show the reason to the user, but retry on Timeout.
Application errors with anyhow
At the top of an application (a main function, a web handler, a CLI command), you usually do not match on every case. You want to stop, log a clear message and the chain of causes. The anyhow crate gives one error type that can hold any error, plus context:
use anyhow::{Context, Result};
fn load_settings(path: &str) -> Result<u64> {
let text = std::fs::read_to_string(path)
.with_context(|| format!("could not read {path}"))?;
let limit = text
.trim()
.parse::<u64>()
.context("free shipping limit is not a number")?;
Ok(limit)
}
fn main() -> Result<()> {
let limit = load_settings("shop.toml")?;
println!("free shipping over {limit} cents");
Ok(())
}
If the file is missing, the program prints the context message first and then the cause, so the person on call knows what failed and why.
The usual rule: thiserror in libraries, anyhow in applications. It is a habit, not a law. Some application layers also want typed errors, for example to map each case to an HTTP status code.
Avoid unwrap in libraries
The unwrap method takes the value out of a Result or an Option, and panics if there is none. It is fine in tests and small scripts. In a library it is a trap:
- The caller cannot recover. They wanted to show “bad price file, line 3” to the user, but the library already panicked.
- In a server, a panic kills the thread or the task, and the request gets no useful answer.
- The panic message is weak, for example “called Result::unwrap on an Err value”, with no business context.
If something really can never fail, use the expect method with a message that says why it cannot fail. Then a panic means a bug, and the message helps to find it.
let limit: u64 = "5000".parse().expect("constant is a valid number");
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| unwrap on user input in a library | The whole thread or task panics. | Return a Result with a clear error type. |
| A generic method in a trait used as dyn | Compile error E0038: not dyn compatible. | Take a concrete type, or add a where clause that requires Self to be Sized. |
| Box of dyn everywhere “to be flexible” | Slower calls, no inlining. | Generics or an enum when the types are known. |
| String as the error type | Callers cannot match on the cases. | An error enum (thiserror). |
| Using map_err to throw the original error away | The real cause is lost. | Keep it as the source, or add context with anyhow. |
| anyhow in the public API of a library | Callers cannot match on the error. | A typed error enum in libraries. |
| Panicking for bad input | A crash instead of a message. | Panic only for bugs. |
Summary in 7 lines
- A trait lists the methods a type promises. Default methods are written once.
- Generics are monomorphized: one fast copy for each type, chosen at compile time.
- A trait object (dyn) uses a vtable: one copy of the code, chosen at run time.
- A trait with generic methods, or methods returning Self, is not dyn compatible.
- Errors are values of the Result type. A panic is only for bugs.
- The question mark operator returns early on Err and converts the error with From.
- Libraries return typed errors (thiserror) and avoid unwrap; applications add context (anyhow).