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.

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
// 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;// 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// 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
| Form | Syntax | Size | Use |
|---|---|---|---|
| Named-field struct | struct S { a: u8 } | Fields only (plus padding) | Anything with more than one field |
| Tuple struct | struct S(u8, String) | Fields only | Newtypes, wrapper types |
| Unit struct | struct S; | Zero-sized | Marker, 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 + tag | Tagged unions, state machines |
Option<T> | enum Option<T> { Some(T), None } | size_of::<T>() with niche | Absence |
Result<T, E> | enum Result<T, E> { Ok(T), Err(E) } | Max of both + tag | Failure |
| Receiver | Caller must have | Consumes | Use for |
|---|---|---|---|
&self | A shared borrow | No | Queries, formatting, accessors |
&mut self | A mutable borrow | No | In-place updates |
self | Ownership | Yes | Builders, into_* conversions, chaining |
self: Box<Self> | A boxed value | Yes | Consuming trait objects |
| Derive | Provides | Requires |
|---|---|---|
Debug | {:?} formatting | Nothing |
Clone | .clone() | All fields Clone |
Copy | Implicit copy | All fields Copy, no Drop |
PartialEq / Eq | ==, != | Fields comparable |
PartialOrd / Ord | <, >, sort | Fields ordered |
Hash | Usable as HashMap key | Fields Hash |
Default | Default::default() | All fields Default |
Practical edge cases and deep dives
1. Struct update syntax moves, including the source
#[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
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
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 payloadFor a data enum, write the mapping explicitly. Casting via mem::discriminant compares tags but does not extract fields:
use std::mem::discriminant;
let a = Msg::Quit;
let b = Msg::Quit;
assert_eq!(discriminant(&a), discriminant(&b)); // tag equality, ignores payload4. Matching moves the value unless you match a reference
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
// 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
#[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
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 / symptom | Cause | Fix |
|---|---|---|
E0063 missing field | Struct literal without all fields | Provide the field or ..Default::default() |
E0560 struct has no field named | Typo or wrong struct | Check the definition |
E0382 after struct update syntax | ..base moved fields | ..base.clone() |
E0599 no method named | Method not in scope or on the wrong type | impl it, or import the trait |
E0308 after newtype refactor | Passing u64 where UserId expected | Wrap at the boundary: UserId(n) |
E0605 non-primitive cast | as on a data-carrying enum | match on variants |
E0507 cannot move out of borrowed content | Matching a struct behind & | Match references or clone() |
PartialEq needed for assert_eq! | No derive | #[derive(PartialEq)] |
HashMap key rejected | No Hash/Eq derive | Derive both |
Default not implemented | Missing derive or field | #[derive(Default)] |
| "cannot borrow as mutable" on a builder call | Binding not mut with &mut self setters | Use consuming self setters |
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.