Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust Structs and Enums: Tuple Structs, Methods, and Algebraic Data Types

Struct is and, enum is or. Newtypes that stop argument mix-ups, receivers that decide ownership, and state machines where illegal states cannot be built.

~3 min readRust
#Rust#Data Structures#Syntax
3D illustration of algebraic enum variants nested in one container beside a struct field grid with method blocks

Quick Summary

A Rust struct groups named data; an enum is a tagged union that holds one of several shapes. Together they are algebraic data types: struct is "and" (every field is present), enum is "or" (exactly one variant is active), and nesting them expresses most domain models without a class hierarchy. Option<T> and Result<T, E> are ordinary enums from the standard library, which is why the same match handles them.

Three syntax forms of struct exist and each has a purpose. Named-field structs are the default. Tuple structs (struct Meters(f64)) give meaning to a single value without runtime cost — the newtype pattern. Unit structs (struct Marker;) carry no data and serve as type-level flags or trait markers.

Behaviour lives in impl blocks: methods take self, &self, or &mut self, associated functions take neither and are called as Type::new(). Enums can hold data per variant (Option<T>), no data at all (Color::Red), or both. Deriving Debug, Clone, PartialEq, and Hash covers most day-to-day needs; anything with custom invariants needs a hand-written impl.

Basic syntax and query signatures

rust
// Named fields #[derive(Debug, Clone, PartialEq)] struct Point { x: f64, y: f64 } impl Point { // Associated function: no self fn new(x: f64, y: f64) -> Self { Point { x, y } } // field init shorthand fn origin() -> Self { Self::new(0.0, 0.0) } // &self: read-only method fn distance(&self, other: &Point) -> f64 { ((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt() } // &mut self: mutating method fn translate(&mut self, dx: f64, dy: f64) { self.x += dx; self.y += dy; } // self: consuming method, for builders and conversions fn scaled(mut self, k: f64) -> Self { self.x *= k; self.y *= k; self } } // Tuple struct: newtype #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] struct UserId(u64); #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] struct OrderId(u64); // Unit struct struct Marker;
rust
// Enums with data per variant #[derive(Debug)] enum Shape { Circle { r: f64 }, Rect { w: f64, h: f64 }, Point, } impl Shape { fn area(&self) -> f64 { match self { Shape::Circle { r } => std::f64::consts::PI * r * r, Shape::Rect { w, h } => w * h, Shape::Point => 0.0, } } } // C-like enum with explicit discriminants and a cast #[derive(Debug, Clone, Copy, PartialEq)] #[repr(u8)] enum Level { Low = 1, Mid = 5, High = 9 } let code = Level::Mid as u8; // 5
rust
// State machine: the enum makes illegal states unrepresentable enum Job { Queued { attempts: u8 }, Running { started: std::time::Instant, worker: String }, Done { finished: std::time::Instant }, Failed { error: String, attempts: u8 }, } // Struct update syntax, Default, and derive-heavy models #[derive(Default)] struct Config { host: String, port: u16, tls: bool } let base = Config { host: "localhost".into(), port: 5432, tls: false }; let prod = Config { host: "db.internal".into(), ..base.clone() };

Key comparison table

FormSyntaxSizeUse
Named-field structstruct S { a: u8 }Fields only (plus padding)Anything with more than one field
Tuple structstruct S(u8, String)Fields onlyNewtypes, wrapper types
Unit structstruct S;Zero-sizedMarker, stateless impl target
Enum (no data)enum E { A, B }Discriminant (1 byte by default)Category, state
Enum (with data)enum E { A(u8), B }Largest variant + tagTagged unions, state machines
Option<T>enum Option<T> { Some(T), None }size_of::<T>() with nicheAbsence
Result<T, E>enum Result<T, E> { Ok(T), Err(E) }Max of both + tagFailure
ReceiverCaller must haveConsumesUse for
&selfA shared borrowNoQueries, formatting, accessors
&mut selfA mutable borrowNoIn-place updates
selfOwnershipYesBuilders, into_* conversions, chaining
self: Box<Self>A boxed valueYesConsuming trait objects
DeriveProvidesRequires
Debug{:?} formattingNothing
Clone.clone()All fields Clone
CopyImplicit copyAll fields Copy, no Drop
PartialEq / Eq==, !=Fields comparable
PartialOrd / Ord<, >, sortFields ordered
HashUsable as HashMap keyFields Hash
DefaultDefault::default()All fields Default

Practical edge cases and deep dives

1. Struct update syntax moves, including the source

rust
#[derive(Clone)] struct Cfg { host: String, port: u16 } let base = Cfg { host: "a".into(), port: 1 }; let other = Cfg { port: 2, ..base }; // host is moved out of base // println!("{:?}", base.host); // E0382: partially moved

..base moves every field it takes. If base must survive, either ..base.clone() or implement Copy (only possible when every field is Copy, so never with String).

2. Newtypes stop argument mix-ups at compile time

rust
fn transfer(from: UserId, to: UserId, amount_cents: u64) { /* ... */ } let user = UserId(7); let order = OrderId(9); // transfer(user, order, 100); // E0308: expected `UserId`, found `OrderId`

Two u64 parameters would have compiled and transferred money the wrong way. The tuple struct costs nothing at runtime — it is erased — and it also lets you impl foreign traits on it, which raw u64 cannot do.

3. Data-carrying enums cannot be cast with as

rust
enum Msg { Text(String), Quit } // let n = Msg::Quit as u8; // only allowed for field-less enums #[repr(u8)] enum Unit { A = 1, B = 2 } let n = Unit::A as u8; // fine: no payload

For a data enum, write the mapping explicitly. Casting via mem::discriminant compares tags but does not extract fields:

rust
use std::mem::discriminant; let a = Msg::Quit; let b = Msg::Quit; assert_eq!(discriminant(&a), discriminant(&b)); // tag equality, ignores payload

4. Matching moves the value unless you match a reference

rust
enum Cmd { Set(String), Get } let cmd = Cmd::Set("x".into()); match cmd { Cmd::Set(s) => println!("{s}"), // moves s out Cmd::Get => {} } // println!("{:?}", cmd); // E0382 // Non-consuming match &cmd { Cmd::Set(s) => println!("{s}"), // s: &String Cmd::Get => {} }

Because Cmd is not Copy (it contains a String), the match by value consumes it. Matching &cmd is the default choice for anything that needs the value afterwards.

5. Illegal states made unrepresentable

rust
// Easy to misuse: both flags can be true struct Job { running: bool, finished: bool, error: Option<String> } // Impossible: exactly one variant at a time enum JobState { Queued, Running, Finished, Failed(String) }

The enum version removes the class of bugs where running && finished is true, and the compiler then forces every consumer to handle all four states when a new one is added.

6. Builders for many optional fields

rust
#[derive(Default)] struct Request { url: String, method: Option<String>, timeout_ms: Option<u64>, retries: Option<u32>, } impl Request { fn new(url: impl Into<String>) -> Self { Request { url: url.into(), ..Default::default() } } fn method(mut self, m: impl Into<String>) -> Self { self.method = Some(m.into()); self } fn timeout(mut self, ms: u64) -> Self { self.timeout_ms = Some(ms); self } fn build(self) -> Result<Self, &'static str> { if self.url.is_empty() { return Err("url required"); } Ok(self) } } let req = Request::new("https://api").method("POST").timeout(5_000).build()?;

Consuming self in each setter makes the chain safe to use once; build is the place to validate invariants that the type cannot express.

7. Method resolution and impl on foreign types

rust
impl std::fmt::Display for UserId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "user-{}", self.0) } } // Generic impl blocks apply to all instantiations impl<T: std::fmt::Debug> Wrapper<T> { fn debug_print(&self) { println!("{:?}", self.value); } }

A newtype is the only way to implement a foreign trait (Display) for a foreign type's shape (u64), because of the orphan rule. That is often reason enough for the wrapper, independent of type safety.

Common mistakes and runtime errors

Error / symptomCauseFix
E0063 missing fieldStruct literal without all fieldsProvide the field or ..Default::default()
E0560 struct has no field namedTypo or wrong structCheck the definition
E0382 after struct update syntax..base moved fields..base.clone()
E0599 no method namedMethod not in scope or on the wrong typeimpl it, or import the trait
E0308 after newtype refactorPassing u64 where UserId expectedWrap at the boundary: UserId(n)
E0605 non-primitive castas on a data-carrying enummatch on variants
E0507 cannot move out of borrowed contentMatching a struct behind &Match references or clone()
PartialEq needed for assert_eq!No derive#[derive(PartialEq)]
HashMap key rejectedNo Hash/Eq deriveDerive both
Default not implementedMissing derive or field#[derive(Default)]
"cannot borrow as mutable" on a builder callBinding not mut with &mut self settersUse consuming self setters

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.