
Add powers + and Display powers {}, so Money reads like a built-in.Understand it
a + b calls Add::add, {} calls Display::fmt, and .into() calls Into, which you get for free by implementing From. Because they are normal traits, your own types participate in the same syntax as the built-in ones, and the compiler checks the result type at every use.
Operator syntax in Rust is backed by trait implementations. a + b invokes Add::add, and the implementation selects an associated Output type. In the Money example, adding two money values yields another Money; the newtype prevents an ordinary integer from being treated as money without an explicit conversion. This is useful because a small wrapper can make invalid operations harder to write while keeping familiar arithmetic syntax.
Do not overload an operator merely because you can. Readers expect + to combine values predictably; surprising side effects or hidden I/O make code harder to trust. Decide whether addition consumes operands, borrows them, or needs multiple implementations. The sample's Money is Copy, so by-value addition is cheap. A large owned type may benefit from reference-based implementations to avoid unnecessary moves. Use checked arithmetic or a wider representation if overflow matters for the domain.
Display and Debug serve different readers: Display is an intentional user-facing representation, while Debug helps inspect a value during development. From<T> for U expresses an infallible conversion and provides Into<U> automatically; a fallible conversion belongs in TryFrom. Implement a formatter for Money, add two values, and compare the result with your expected units. Keep the trait's semantic promise as clear as its syntax.
For a domain type, specify units and error behavior before implementing arithmetic. Money measured in cents should not add to a temperature, and a conversion from floating-point input may be lossy or fallible. A From implementation must not hide a failure; use TryFrom when invalid input is possible. Write tests for zero, negative values if allowed, and overflow boundaries. Operator syntax makes code compact, but the type system and tests must keep its meaning precise.
Read the code
use std::fmt;
use std::ops::Add;
#[derive(Debug, Clone, Copy)]
struct Money(i64);
impl Add for Money {
type Output = Money;
fn add(self, other: Money) -> Money {
Money(self.0 + other.0)
}
}
impl fmt::Display for Money {
fn fmt(
&self,
f: &mut fmt::Formatter<'_>,
) -> fmt::Result {
write!(f, "{}", self.0 as f64 / 100.0)
}
}Add powers + and Display powers {}, so Money reads like a built-in.
Practice starter
struct Money(i64);
impl From<u32> for Money {
fn from(v: u32) -> Money {
Money(i64::from(v))
}
}
let m: Money = 500_u32.into();Try it
Give Money a From<u32> implementation and convert with .into().
What success looks like: 500_u32.into() produces a Money, and you can say where its Into came from.
Check your understanding
Why does .into() work without writing an Into impl?
Reveal the answer
- Into is derived alongside From automatically
- A blanket impl gives Into to everything that implements From
- The compiler special-cases .into() for every type
The standard library has impl<T, U: From<T>> Into<U> for T.
Go deeper
Common misconception: “To use .into(), you have to implement both From and Into.”
Write only From. The standard library's blanket impl<T, U: From<T>> Into<U> for T provides Into, so 500_u32.into() already works, and a matching hand-written Into conflicts with it.
- Match syntax to trait: For
Money,a + bcallsAdd::addand{}callsDisplay::fmt. In the practice code,500_u32.into()callsInto::into, which forwards toFrom<u32>. - Predict before checking: Predict what
println!("{}", Money(150) + Money(275));prints, given thatfmtdivides by 100. Then predict the value ofm.0after500_u32.into(). - Compare with evidence: The print shows
4.25, andm.0is500. All of it goes through ordinary trait methods you can read.
Transfer challenge: Add impl From<i64> for Money beside the u32 version and convert with let m: Money = 7_i64.into();. Then remove Copy from the example's derive and read what happens when a Money bound to a is used again after a + b.
Connections
- Associated Types: One output type per implementation
- Moves Across Functions: Parameters can take, borrow, or copy a value
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Operator Traits (courseId "ownership", lessonId "operator-traits") Link: https://crabrix.com/learn/ownership/operator-traits/ Goal: Implement From, and Into is generated for you — never implement both. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=ownership/operator-traits) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.