Structuring Related Data

Structuring Related Data in Rust: A shipping clerk has two ways to record a parcel. The first is to write three numbers on a blank slip: 4, 250, 44.

The Analogy: The Pre-Printed Form

A shipping clerk has two ways to record a parcel. The first is to write three numbers on a blank slip: 4, 250, 44. The second is to fill in a pre-printed form with labelled boxes -- Weight (kg): 4, Value (pounds): 250, Country code: 44. Both carry exactly the same three numbers, and the blank slip is quicker.

The slip is also impossible to read six months later, and -- much worse -- impossible to check. Swap the value and the country code on the printed form and anyone notices immediately, because 250 is not a country code and 44 is a suspiciously cheap parcel. On the blank slip, "4, 44, 250" is precisely as plausible as "4, 250, 44". The labels were not decoration; they were the only thing standing between you and a silent error.

There is a third form in the drawer, and it looks like a waste of paper: a form with a single box, labelled "Kilograms". Why print a whole form for one number? Because a number written in that box can never be mistaken for a number written in the "Pounds" box, even though both boxes hold nothing but a number. The box is the point.

Rust gives you all three. A struct with named fields is the pre-printed form, and it is what you should reach for by default. A tuple struct replaces the labels with positions, which is fine when there is only one sensible reading. And a one-field tuple struct -- the "newtype" -- is the single-box form: it occupies not one extra byte at run time, and it turns an entire category of mix-up from a support ticket into a compile error.


Syntax or Core Structure

All four shapes, plus the two pieces of syntax that make structs pleasant to write: field init shorthand and struct update.

// Named fields: the pre-printed form.
#[derive(Debug)]
struct Parcel {
    weight_kg: f64,
    value_pence: u32,
    country: String,
    fragile: bool,
}

// A tuple struct: same idea, fields addressed by position.
#[derive(Debug)]
struct Dimensions(u32, u32, u32);

// A newtype: one field, purely to keep two integers apart.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Grams(u32);

// A unit struct: a named type carrying no data at all.
#[derive(Debug)]
struct Metric;

fn main() {
    let mut p = Parcel {
        weight_kg: 4.0,
        value_pence: 25_000,
        country: String::from("GB"),
        fragile: false,
    };

    // Dot notation reads and writes; writing needs a mut binding.
    println!("weight = {}, country = {}", p.weight_kg, p.country);
    p.fragile = true;
    println!("{p:?}");

    // Field init shorthand: a local with the field's name fills it in.
    let country = String::from("FR");
    let value_pence = 900;
    let small = Parcel { weight_kg: 0.2, value_pence, country, fragile: false };
    println!("{small:?}");

    // Struct update syntax takes the remaining fields from another value.
    let heavier = Parcel { weight_kg: 12.5, ..small };
    println!("{heavier:?}");

    // Tuple structs index by position.
    let d = Dimensions(30, 20, 10);
    println!("volume = {}", d.0 * d.1 * d.2);

    // A newtype is an ordinary struct; .0 gets the value back out.
    let g = Grams(4000);
    println!("{g:?} is {} kg", g.0 as f64 / 1000.0);

    println!("{:?}", Metric);
}

Output:

weight = 4, country = GB
Parcel { weight_kg: 4.0, value_pence: 25000, country: "GB", fragile: true }
Parcel { weight_kg: 0.2, value_pence: 900, country: "FR", fragile: false }
Parcel { weight_kg: 12.5, value_pence: 900, country: "FR", fragile: false }
volume = 6000
Grams(4000) is 4 kg
Metric

Note the difference between {} and {:?} on weight_kg: Display prints 4 for 4.0, Debug prints 4.0. And note the order of the last two Parcel lines -- small had to be printed before ..small was used, because country is a String and struct update moves it. After that line, small is partially moved and cannot be printed as a whole again.

Writing to a field needs the same mut that writing to any other binding needs:

struct Config {
    retries: u32,
}

fn main() {
    let c = Config { retries: 3 };
    c.retries = 5;
}

Output:

error[E0594]: cannot assign to `c.retries`, as `c` is not declared as mutable
 --> src/main.rs:7:5
  |
7 |     c.retries = 5;
  |     ^^^^^^^^^^^^^ cannot assign
  |
help: consider changing this to be mutable
  |
6 |     let mut c = Config { retries: 3 };
  |         +++

Mutability belongs to the binding, not to individual fields. There is no way to mark one field of a struct mutable and the rest not -- if you need that distinction, it is a sign the struct wants splitting, or wants a method that guards the change.


Technical Depth: Shapes, Methods, and Layout

Four shapes, one concept

ShapeDeclared asAccessed byReach for it when
named fieldsstruct P { a: u32, b: u32 }p.aalmost always
tuple structstruct P(u32, u32)p.0two fields with an obvious order
newtypestruct P(u32)p.0a unit or identity you want enforced
unit structstruct P;--a marker type with no data

The semicolon on the unit struct matters. struct P; makes P itself a value. struct P(); is a tuple struct with zero fields, so the value is written P(). struct P {} is a named-field struct with no fields, so the value is written P {}. All three are distinct, and only the first is what people mean by a unit struct.

Methods and associated functions

An impl block attaches functions to the type. A function whose first parameter is some form of self is a method, called with dot notation; one without is an associated function, called with Type::name.

#[derive(Debug)]
struct Rect {
    w: u32,
    h: u32,
}

impl Rect {
    // Associated function: no self. Self is an alias for Rect.
    fn new(w: u32, h: u32) -> Self {
        Self { w, h }
    }

    fn square(side: u32) -> Self {
        Self::new(side, side)
    }

    // &self borrows: reads without consuming.
    fn area(&self) -> u32 {
        self.w * self.h
    }

    fn can_hold(&self, other: &Rect) -> bool {
        self.w > other.w && self.h > other.h
    }

    // &mut self mutates in place; returning &mut Self allows chaining.
    fn scale(&mut self, factor: u32) -> &mut Self {
        self.w *= factor;
        self.h *= factor;
        self
    }

    // self consumes, so the old value is gone afterwards.
    fn into_square(self) -> Rect {
        let side = self.w.max(self.h);
        Rect { w: side, h: side }
    }
}

fn main() {
    let a = Rect::new(30, 50);
    let b = Rect::square(10);
    println!("a = {a:?}, area = {}", a.area());
    println!("b = {b:?}, area = {}", b.area());
    println!("a can hold b: {}", a.can_hold(&b));

    let mut c = Rect::new(3, 4);
    c.scale(2).scale(3);
    println!("c = {c:?}, area = {}", c.area());

    let sq = a.into_square();
    println!("sq = {sq:?}");
}

Output:

a = Rect { w: 30, h: 50 }, area = 1500
b = Rect { w: 10, h: 10 }, area = 100
a can hold b: true
c = Rect { w: 18, h: 24 }, area = 432
sq = Rect { w: 50, h: 50 }
First parameterThe method mayThe caller afterwards
&selfread fieldsstill owns the value
&mut selfread and write fieldsstill owns the value
selfdo anything, including move fields outno longer has the value
nonenot touch an instanceunaffected

Choosing between these is the single most consequential decision in a struct's API, because it is visible to every caller forever. The convention is that a self-taking transformation is named into_something, which is why into_square reads as a warning that a is being spent.

What a struct owns

A struct owns whatever its fields own, and its fields drop when it drops, in declaration order.

Field typeThe struct owns the dataNeeds a lifetime parameter
Stringyesno
Vec<T>yesno
Box<T>yesno
u32, bool, f64yes (inline)no
&strno, it borrowsyes: struct S<'a> { s: &'a str }
&mut [T]no, it borrowsyes

That last pair is worth planning around. The moment one field is a reference, the struct grows a lifetime parameter, and every function signature, every other struct that contains it, and every trait implementation has to carry that parameter too. It is the right call for a zero-copy parser and the wrong call for a config object. Start with owned fields.

Because ownership is per field, a struct can be partially moved:

struct User {
    name: String,
    id: u32,
}

fn main() {
    let u = User { name: String::from("ada"), id: 1 };
    let name = u.name;
    println!("{name} has id {}", u.id);
}

Output:

ada has id 1

u.name moved out, but u.id is still perfectly readable -- the compiler tracks the fields separately. What you cannot do afterwards is use u as a whole: passing it to a function, or printing it with {:?}, would need all of it back.

Derives do the boring work

DeriveWhat it gives youRequires
Debug{:?} and {:#?} formattingevery field Debug
Clonean explicit .clone()every field Clone
Copyimplicit copies instead of movesClone, every field Copy, no Drop
PartialEq== and !=every field PartialEq
Eqmarks equality as totalPartialEq
PartialOrd, Ord<, >, and sortingthe Eq family
Hashuse as a HashMap keyevery field Hash
DefaultT::default() and ..Default::default()every field Default

Three precise details. #[derive(Copy)] on its own does not compile, because Copy has Clone as a supertrait -- you get error[E0277]: the trait bound ... Clone is not satisfied and must write #[derive(Clone, Copy)]. Derived PartialOrd and Ord compare fields in declaration order, lexicographically, so reordering the fields of a sorted struct silently changes the sort. And derived Default gives every field its own default, which for numbers is zero and for String is empty -- meaningful for a config, misleading for an id.

Field order is not memory order

Unless you say otherwise, the compiler is free to rearrange fields to minimise padding.

use std::mem::{align_of, size_of};

#[allow(dead_code)]
struct Naive {
    a: u8,
    b: u64,
    c: u8,
}

fn main() {
    println!("sum of field sizes = {}", 1 + 8 + 1);
    println!("size_of Naive      = {}", size_of::<Naive>());
    println!("align_of Naive     = {}", align_of::<Naive>());
}

Output (on a 64-bit target):

sum of field sizes = 10
size_of Naive      = 16
align_of Naive     = 8

The u64 needs eight-byte alignment, so the compiler puts it first and packs both u8 fields after it: eight plus one plus one is ten, rounded up to a multiple of the alignment, giving sixteen. Add #[repr(C)] and the declared order becomes binding, which forces seven bytes of padding after a and another seven after c, taking the same three fields to twenty-four. Use repr(C) when the layout is part of an interface -- talking to C, or reading a file format -- and leave it off otherwise.


Real World Example: An Invoice That Cannot Mix Up Its Units

Money bugs are almost never arithmetic bugs. They are unit bugs: pounds added to pence, a percentage multiplied as though it were an amount, a quantity passed where a rate was expected. All three of those are i64 at run time, so a language that only sees i64 cannot help. Newtypes make the compiler see the difference.

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
struct Pence(i64);

#[derive(Debug, Clone, Copy)]
struct BasisPoints(i64);

#[derive(Debug, Clone, Copy)]
struct Quantity(u32);

#[derive(Debug)]
struct LineItem {
    sku: String,
    unit_price: Pence,
    quantity: Quantity,
    discount: BasisPoints,
}

impl Pence {
    fn zero() -> Self {
        Pence(0)
    }

    fn scale(self, q: Quantity) -> Self {
        Pence(self.0 * q.0 as i64)
    }

    // One basis point is 0.01 per cent, so 2500 bp is a quarter off.
    fn less(self, bp: BasisPoints) -> Self {
        Pence(self.0 - self.0 * bp.0 / 10_000)
    }

    fn plus(self, other: Pence) -> Self {
        Pence(self.0 + other.0)
    }

    fn pounds(self) -> String {
        format!("{}.{:02}", self.0 / 100, self.0 % 100)
    }
}

impl LineItem {
    fn new(sku: &str, unit_price: Pence, quantity: Quantity) -> Self {
        Self {
            sku: sku.to_string(),
            unit_price,
            quantity,
            discount: BasisPoints(0),
        }
    }

    fn with_discount(mut self, bp: BasisPoints) -> Self {
        self.discount = bp;
        self
    }

    fn total(&self) -> Pence {
        self.unit_price.scale(self.quantity).less(self.discount)
    }
}

fn invoice(items: &[LineItem]) -> Pence {
    items.iter().fold(Pence::zero(), |acc, item| acc.plus(item.total()))
}

fn main() {
    let items = [
        LineItem::new("KB-01", Pence(4999), Quantity(2)),
        LineItem::new("MS-07", Pence(1250), Quantity(3)).with_discount(BasisPoints(1000)),
        LineItem::new("CB-22", Pence(899), Quantity(10)).with_discount(BasisPoints(2500)),
    ];

    for item in &items {
        println!(
            "{:<6} {:>3} x {:>8} = {:>9}",
            item.sku,
            item.quantity.0,
            item.unit_price.pounds(),
            item.total().pounds()
        );
    }

    let total = invoice(&items);
    println!("{:<6} {:>3}   {:>8}   {:>9}", "TOTAL", "", "", total.pounds());
    println!("raw = {total:?}");
}

Output:

KB-01    2 x    49.99 =     99.98
MS-07    3 x    12.50 =     33.75
CB-22   10 x     8.99 =     67.43
TOTAL                      201.16
raw = Pence(20116)

Now try to make the classic mistake:

fn main() {
    let price = Pence(4999);
    let total = price.less(price);
    println!("{}", total.pounds());
}

Output (first part of the message):

error[E0308]: mismatched types
 --> src/main.rs:3:28
  |
3 |     let total = price.less(price);
  |                       ---- ^^^^^ expected `BasisPoints`, found `Pence`
  |                       |
  |                       arguments to this method are incorrect

The rest of the message points at the definition of less to show which parameter was meant. The important thing is that this is a build failure, not a wrong invoice. Without the newtypes, price.less(price) would be 4999 - 4999 * 4999 / 10000, which is a large negative number that would have sailed through to a customer.

The three newtypes cost nothing. Pence is one i64 and size_of::<Pence>() equals size_of::<i64>(); there is no box, no tag, and no run-time check. The entire benefit is at compile time, extracted from the fact that the compiler treats two structurally identical types as unrelated unless you tell it otherwise. This is the cheapest safety Rust offers, and the most consistently skipped.

Keeping the arithmetic in impl Pence rather than scattered through the calling code means the discount rule exists in exactly one place, and total() reads as a sentence: take the unit price, scale it by the quantity, take the discount off. with_discount takes mut self and returns Self, which is what makes the chained construction in main work while leaving discount an ordinary field with a sensible default -- no Option, no half-built value that other code has to defend against.

Two rough edges are worth naming rather than hiding, because they are exactly the kind of thing a single place makes easy to fix. pounds() is only correct for non-negative amounts: Pence(-5).pounds() produces 0.-5, because -5 / 100 is 0 and -5 % 100 is -5. And less truncates rather than rounds: a quarter off 8990 comes out as 6743, because the exact discount of 2247.5 is cut down to 2247 by integer division, which leaves the half penny with the seller rather than the customer. Both behaviours are defensible; neither should be an accident, and with the arithmetic gathered into one impl block there is a single obvious place to write the rule down.


Common Mistakes

  1. Forgetting mut on the binding. c.retries = 5 on a let c = ... gives error[E0594]: cannot assign to c.retries, as c is not declared as mutable. Mutability is a property of the binding, so there is no per-field version of it.
  1. Writing #[derive(Copy)] alone. Copy requires Clone as a supertrait, so the derive fails with error[E0277] until you write #[derive(Clone, Copy)]. And a struct with even one non-Copy field, such as a String, cannot be Copy at all.
  1. Expecting ..base to leave base usable. Struct update moves every non-Copy field it takes. After let b = Parcel { weight_kg: 1.0, ..a }; the String field has left a, and a can no longer be used as a whole. Write ..a.clone() if you need both.
  1. Using a struct after moving one field out. Moving u.name out is legal and u.id still reads fine, but println!("{u:?}") or passing u to a function now fails with error[E0382], because those need the whole value.
  1. Taking self when &self was meant. A method declared fn area(self) -> u32 consumes the rectangle, so r.area() can be called exactly once. Reserve self for genuine transformations and name them into_* so callers are warned.
  1. Numbered fields past two. order.0, order.3, order.5 is unreadable at review time and unfixable when someone inserts a field in the middle. Tuple structs earn their keep at one or two fields; beyond that, name them.
  1. Reordering fields on a struct that derives Ord. Derived comparison walks the fields in declaration order, so moving priority below created_at changes what .sort() does without changing a single line of sorting code.
  1. Assuming memory layout follows the declaration. By default the compiler reorders fields to reduce padding, so size_of is often smaller than the sum of the field sizes and sometimes larger than you expect. If a byte layout matters, say #[repr(C)] explicitly.
  1. Confusing the three empty shapes. struct M; is a unit struct whose value is M; struct M(); needs M(); struct M {} needs M {}. They are three different types with three different construction syntaxes, and mixing them up produces a puzzling expected value, found struct error.

Best Practices

  • Use named fields by default and reach for a tuple struct only when there is exactly one sensible reading of the positions -- a wrapper, a coordinate pair, a newtype.
  • Newtype any primitive that carries a unit or an identity. UserId(u64) and OrderId(u64) cost nothing at run time and make an entire class of argument-swap bug impossible.
  • Take &self unless you need to mutate or consume. It is the least restrictive signature, and widening it later to &mut self or self breaks callers while narrowing it never does.
  • Give the type a new in its impl block, and derive Default when zeroes and empty strings are genuinely the right defaults. Config { port: 8080, ..Default::default() } then covers the common case in one line.
  • Own your fields -- String and Vec<T> rather than &str and &[T] -- until you have a measured reason not to. A lifetime parameter spreads to every signature that mentions the type.
  • Derive Debug on essentially everything. It costs nothing you will notice and it improves every panic message, every failing assertion, and every dbg! you ever reach for.
  • Keep the field count small and grouped around one invariant. A struct with fifteen fields is usually two structs that have not been separated yet, and the giveaway is a comment splitting the field list into sections.
  • Add a method only when it enforces or computes something. Reaching for a field directly is idiomatic Rust; a get_port() that returns self.port and nothing else is ceremony borrowed from another language.

Practice Exercises

  1. Two temperature scales. Define Celsius(f64) and Fahrenheit(f64) as newtypes, each with a method converting to the other. Add fn warmer_than(&self, other: &Celsius) -> bool to Celsius, then try calling it with a Fahrenheit and record the error code you get. Finally print size_of for both newtypes and for f64, and confirm all three are the same.
  1. A playlist with methods. Define Track { title: String, seconds: u32 } and Playlist { name: String, tracks: Vec<Track> }. Give Playlist an associated new(name: &str), an add(&mut self, title: &str, seconds: u32) -> &mut Self so calls can be chained, total_seconds(&self), longest(&self) -> Option<&Track>, and duration(&self) -> String formatted as minutes and two-digit seconds. Build a three-track playlist with a single chained expression and print all four results.
  1. Defaults and updates. Define ServerConfig { host: String, port: u16, tls: bool, max_connections: u32 } deriving Debug and Default. Write fn dev() -> ServerConfig that sets only port and uses ..Default::default() for the rest, then fn prod() -> ServerConfig that starts from dev() and overrides host and tls. Explain in one sentence why ..dev() is fine but ..some_existing_config would leave that config unusable.
  1. Measure the layout. Define struct Mixed { a: u8, b: u32, c: u8, d: u64 } and print size_of and align_of. Add #[repr(C)] and print them again. Account for the difference field by field, writing down the byte offset of each field under both layouts, then reorder the declaration so that repr(C) produces the same size as the default.