Rust Structs and Enums — Named Fields, Variants, and match
A struct names its fields, an enum names its variants, and each variant can carry its own data. This guide runs programs. The main program builds a Point struct, defines a Shape enum whose Circle variant carries a radius and whose Rect variant carries named width and height fields, and computes both areas with a match that the compiler checks for completeness, printing circle area=12.57 and rect area=12.00. The other programs show field init shorthand, tuple and unit structs, a match with a missing arm that fails with error E0004, Option returning some 7 and none, and struct update syntax moving a String field out of the value it came from.
Written November 12, 2026 · 12 min read
- The main program: a struct, an enum, and a match
- Structs: named fields on one value
- Enums: variants that carry their own data
- match: the compiler counts the arms
What this guide is
Rust gives a program two ways to name a compound value. A struct gives one value several named fields, and every value of that struct has all of those fields. An enum gives one value a set of named variants, and each value is exactly one variant, carrying only the data that variant declares. The two tools answer different questions: a struct says what a value always has, and an enum says which of several shapes a value takes this time. This guide runs one main program that uses both, plus five smaller programs that isolate field init shorthand, the other struct forms, the match completeness rule, the built-in Option enum, and the struct update trap. Every output and every compiler error below is the output of a run.
The main program: a struct, an enum, and a match
struct Point { x: i32, y: i32 }
enum Shape { Circle(f64), Rect { w: f64, h: f64 } }
fn area(s: &Shape) -> f64 {
match s {
Shape::Circle(r) => 3.14159 * r * r,
Shape::Rect { w, h } => w * h,
}
}
fn main() {
let p = Point { x: 3, y: 4 };
println!("point x={} y={}", p.x, p.y);
println!("circle area={:.2}", area(&Shape::Circle(2.0)));
println!("rect area={:.2}", area(&Shape::Rect { w: 3.0, h: 4.0 }));
}
The exact output:
point x=3 y=4
circle area=12.57
rect area=12.00
The struct produced the first line, and the enum produced the other two. Point { x: 3, y: 4 } built a value with named fields, and p.x and p.y read them back. Shape::Circle(2.0) built a value of the Circle variant carrying one number, and Shape::Rect { w: 3.0, h: 4.0 } built a value of the Rect variant carrying two named fields. The area function took a reference to either shape and used match to run a different formula for each variant, binding the data inside the variant to local names as it did so. The sections below take each part in turn.
Structs: named fields on one value
The declaration struct Point { x: i32, y: i32 } defines a type with two fields, x and y, both of type i32. The literal Point { x: 3, y: 4 } fills each field by name, so the order in the literal does not have to match the order in the declaration. A field is read with a dot: p.x is 3 and p.y is 4. A field declared with mut on the binding can be changed the same way, as in p.x = 9, and the change applies to the whole binding, because Rust makes the value mutable or not as a unit rather than field by field.
Field init shorthand removes a repetition that shows up in constructors. When a local variable has the same name as a field, the literal can write the name once instead of writing it as a key and a value. A second program shows the shorthand form next to the other two struct forms:
struct Point { x: i32, y: i32 }
struct Color(i32, i32, i32);
struct AlwaysEqual;
fn main() {
let x = 3;
let y = 4;
let p = Point { x, y };
println!("shorthand x={} y={}", p.x, p.y);
let black = Color(0, 0, 0);
println!("color {} {} {}", black.0, black.1, black.2);
let _subject = AlwaysEqual;
println!("unit struct built");
}
The exact output:
shorthand x=3 y=4
color 0 0 0
unit struct built
Point { x, y } built the same value as Point { x: 3, y: 4 } did in the main program, taking each field value from the variable of the same name. Color is a tuple struct: its fields have types but no names, the literal fills them by position, and the fields read back as black.0, black.1, and black.2. Tuple structs suit values whose meaning is clear from the type name alone, like a color or a point in a system that never names the axes. AlwaysEqual is a unit-like struct, a type with no fields at all; the program built one value of it to show the form exists. A unit-like struct is useful when a type needs to exist, for example to carry behavior, but holds no data.
Enums: variants that carry their own data
The declaration enum Shape { Circle(f64), Rect { w: f64, h: f64 } } defines a type with two variants. A value of type Shape is a circle or a rectangle, never both, and never neither. The Circle variant carries one f64, the radius. The Rect variant carries two named fields, w and h. A third form, a variant with no data at all, works like a plain label; the main program does not need one, but the form exists and the Option section below uses two variants of the built-in kind.
This is where a Rust enum parts company with the C kind. A C enum is a set of named integers: each name stands for a number, and the value carries nothing else. A Rust variant carries the data its declaration lists, and the type system remembers which variant a value is. Shape::Circle(2.0) is not the number 0 with a radius stored somewhere else; the 2.0 travels inside the value. That difference is why the area function can ask a shape for its dimensions without a separate table, a tag field the programmer must keep in sync, or a cast.
Variants live under the enum name. The constructor is Shape::Circle, not bare Circle, and the match arms in the main program spell both variants with the Shape:: prefix. The namespacing keeps two enums free to reuse a variant name without a collision, and it makes every construction site state which enum it is building.
match: the compiler counts the arms
The area function reads a shape with match. Each arm names a pattern on the left and the expression to run on the right. The arm Shape::Circle(r) matches a Circle value and binds the number inside it to the name r, so the right side can compute 3.14159 * r * r. The arm Shape::Rect { w, h } matches a Rect value and binds its two fields to the names w and h. A match is an expression in Rust: the value of the arm that runs is the value of the whole match, and area returns it.
A match must be exhaustive. Every variant of the matched type needs an arm, or a wildcard arm must catch the rest. Deleting the Rect arm from the main program makes the compiler reject the program, and a third program shows the exact failure:
enum Shape { Circle(f64), Rect { w: f64, h: f64 } }
fn area(s: &Shape) -> f64 {
match s {
Shape::Circle(r) => 3.14159 * r * r,
}
}
fn main() { println!("{:.2}", area(&Shape::Circle(2.0))); }
The compiler output, trimmed to the error and the pattern it names:
error[E0004]: non-exhaustive patterns: `&Shape::Rect { .. }` not covered
The error names the missing case and the compiler exits without producing a program. This check is the practical reason enums and match belong together. Adding a variant to an enum makes every match on that enum fail to compile until each match gains an arm for the new variant, so the places that must learn about the new shape are found by the compiler instead of by a search or by a missed case at run time. The Rust Book match chapter states the same rule: patterns must cover every possibility, and the compiler reports the pattern that is not covered.
error[E0004]: non-exhaustive patterns, and the error names &Shape::Rect { .. } as the pattern not covered. Adding a variant to an enum breaks every incomplete match at compile time, on purpose.Option: the built-in enum for a value that may be absent
The standard library defines an enum named Option with two variants, Some carrying a value and None carrying nothing. Rust code returns an Option where another language would return a null or a sentinel, and the caller must match on it before the value inside can be used. A fourth program shows the shape of that contract:
fn describe(v: Option<i32>) -> String {
match v {
Some(n) => format!("some {}", n),
None => String::from("none"),
}
}
fn main() {
println!("{}", describe(Some(7)));
println!("{}", describe(None));
}
The exact output:
some 7
none
Both arms were required, for the same E0004 reason as the Shape match. The caller cannot reach the 7 without writing the arm that binds it, and cannot forget the empty case, because the match will not compile without it. A full treatment of Option, including the combinator methods that work on it, belongs to a later guide; the point here is that the most common enum in Rust programs is one the library already defines, and it works by the same variant and match rules as Shape.
Trap: struct update syntax moves non-Copy fields
... A fifth program shows the form working:struct User { name: String, active: bool, sign_in_count: u64 }
fn main() {
let u1 = User { name: String::from("ana"), active: true, sign_in_count: 3 };
let u2 = User { name: String::from("bo"), ..u1 };
println!("u2 name={} active={} count={}", u2.name, u2.active, u2.sign_in_count);
println!("u1 active={} count={}", u1.active, u1.sign_in_count);
}
The exact output:
u2 name=bo active=true count=3
u1 active=true count=3
The literal named only name, and ..u1 supplied active and sign_in_count. Reading u1.active and u1.sign_in_count after the update still works, because bool and u64 are Copy types: the update copied them, and the original keeps its own copies. The name field is the trap. A String is not Copy, so an update that takes the old name moves it. Changing the fifth program so the update takes every field from u1, and then reading u1.name, fails to compile:
struct User { name: String, active: bool }
fn main() {
let u1 = User { name: String::from("ana"), active: true };
let u2 = User { ..u1 };
println!("u2 {}", u2.name);
println!("u1 {}", u1.name);
}
The compiler output, trimmed to the error and its note:
error[E0382]: borrow of moved value: `u1.name`
= note: move occurs because `u1.name` has type `String`, which does not implement the `Copy` trait
The update syntax follows the same move rules as assignment, which the ownership guide on this site covers in full. Fields of Copy types are copied and stay usable on the original; fields of moving types leave the original partly moved, and the compiler tracks which fields are still available. The working program above reads only the copied fields after the update, and that is the safe pattern: name the moving fields in the literal, or expect them to be gone from the source value.
Which form for which job
| Job | Form | Why |
|---|---|---|
| A value that always has the same parts | struct | Every value carries every field, read by name with a dot |
| A value with a fixed set of parts where names add nothing | tuple struct | Fields read by position, as black.0, under a type name that states the meaning |
| A type that must exist but holds no data | unit-like struct | The type can carry behavior while storing nothing |
| A value that is one of several shapes, each with its own data | enum | Each variant declares the data it carries, and the value is exactly one variant |
| Code that must handle every shape a value can take | match on an enum | The compiler rejects an incomplete match with E0004 and names the missing pattern |
| A value that may be absent | Option |
Some carries the value, None carries nothing, and a match must write both arms |
The deciding question is whether the parts are always present together or whether the value takes one shape at a time. Always together is a struct. One shape at a time, with the shape known to the compiler, is an enum, and match is how the program reads it safely.
Checklist
- Before modeling a value, ask whether its parts are always present together: always together means a struct, one shape at a time means an enum.
- Before writing a struct literal with a variable for every field, use field init shorthand where the names already match.
- Before giving a variant no data, check whether the code that reads the value will need data from it later: a variant can carry a tuple of values or named fields, and changing that later touches every match.
- Before finishing a match, count the variants: every variant needs an arm or a wildcard, and the compiler error names the pattern a missing arm forgot.
- Before using struct update syntax, check which fields move:
Copyfields stay usable on the source value, and a movedStringfield does not. - Before returning a value that may not exist, return an
Option: the caller's match then has to handle theNonearm before the program compiles.
Related guides on this site
- Rust Ownership and Borrowing — Moves, Borrows, and Clones — the move and copy rules behind the struct update trap, including the same E0382 error on a plain assignment.
- Go Structs and Interfaces — Grouping Data and the Method Set That Defines Behavior — the Go counterpart, where a struct groups fields and behavior attaches through methods and interfaces instead of variants.
- C++ Classes and Objects: Your First Class, Constructor, and Methods — the C++ counterpart, where data and behavior are declared together inside a class.
Sources
- The Rust Book, Defining and Instantiating Structs — struct definitions, field init shorthand, struct update syntax, and tuple and unit-like structs.
- The Rust Book, Defining an Enum — enum variants that carry data, and the Option enum and its advantages over null.
- The Rust Book, The match Control Flow Construct — match arms, binding values inside patterns, and the rule that matches must be exhaustive.
- Rust Reference, Enumerations — the enumeration item, its variant forms, and how variant constructors are named.
Keep Exploring
The full Rust hub \u2014 ownership, structs and enums, async, and measured comparisons.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.