Rs
Module 3Structs & MethodsLesson 3 of 918 min

Tuple Structs & Newtypes

Price and Qty newtypes so you cannot mix units by accident.

Newtype pattern

rust
struct Price(f64);
struct Qty(f64);

fn notional(p: Price, q: Qty) -> f64 {
    p.0 * q.0
}

fn main() {
    println!("{:.2}", notional(Price(190.5), Qty(10.0)));
}
Output
1905.00

Calling notional(qty, price) becomes a type error if you swap arguments — a cheap safety win.

Unit structs

rust
struct ExchangeOpen;

Useful as markers/traits later.

When to bother

For teaching and for public APIs of risk systems — yes. For a 10-line script — maybe overkill. Learn the pattern now.

Challenge

Add Bps(f64) and fee(notional: f64, bps: Bps) -> f64 = notional * bps.0 / 10_000.

Tips
  • Newtypes are zero-cost
  • Prefer methods over raw .0 as APIs grow
  • Prevents Price/Qty mixups

Try it live

Tuple Structs & NewtypesRust 2021
Loading editor…
Output
Press Run to compile and execute.