Sub topic 5
Tuple structs and unit structs
This chapter assumes you can define a named-field struct, create an instance, and read its fields. It also assumes you know basic ownership and how to build and run a program with cargo. Named-field structs are the common case. Rust has two lighter forms for situations where field names add nothing.
Tuple structs
A tuple struct has a name but its fields have no names. You access them by position, starting at 0.
#[derive(Debug)]
struct Meters(f64);
#[derive(Debug)]
struct Rgb(u8, u8, u8);
fn main() {
let distance = Meters(12.5);
let red = Rgb(255, 0, 0);
println!("{} m", distance.0);
println!("{:?} has green = {}", red, red.1);
let Rgb(r, g, b) = red;
println!("{r} {g} {b}");
}You can also destructure a tuple struct with a pattern, as the last let shows. The pattern must name the struct type.
Distinct types with identical shapes
Two tuple structs with the same field types are still different types. The compiler does not treat them as interchangeable.
struct Meters(f64);
struct Feet(f64);
fn describe(m: Meters) -> String {
format!("{} m", m.0)
}
fn main() {
let a = Meters(3.0);
let _b = Feet(3.0);
println!("{}", describe(a));
// describe(_b); // error: expected `Meters`, found `Feet`
}This is the main reason to choose a tuple struct over a plain tuple like (f64,). A plain tuple carries no meaning, so a mix-up between units compiles without complaint. A named wrapper type turns that mistake into a compile error. A later chapter builds on this idea as the newtype pattern.
Unit structs
A unit struct has no fields at all. You write the name and a semicolon.
struct Marker;
fn main() {
let _m = Marker;
}A value of a unit struct takes up zero bytes. You use one when you need a type but have no data to store. It is most useful as a type that implements a trait, because a trait implementation needs a type to attach to.
struct Greeter;
impl Greeter {
fn hello(&self) -> &'static str {
"hello"
}
}
fn main() {
println!("{}", Greeter.hello());
}Writing Greeter alone is already a complete value, so no parentheses are needed.
Choosing a form
| Form | Syntax | Fields accessed by | Use when |
|---|---|---|---|
| Named-field struct | `struct P { x: i32 }` | name | Fields have distinct meanings |
| Tuple struct | `struct P(i32);` | position | One field, or an obvious order |
| Unit struct | `struct P;` | none | You need a type but no data |
Exercise
Given struct Seconds(u32); and struct Minutes(u32);, why does passing a Minutes value to a function that takes Seconds fail to compile, even though both wrap a u32?
Show answer
Each tuple struct declaration creates a new, distinct type. The compiler checks the struct name, not the field types, so Minutes and Seconds are not interchangeable. This is what makes tuple structs useful for preventing unit mix-ups.
Exercise
Write a unit struct named Token, then create a value of it and bind it to a variable.
Show answer
struct Token; followed by let t = Token; inside a function. No parentheses or braces are used when creating a unit struct value.