Sub topic 5
Tuple structs and unit structs
This chapter assumes you can define a struct with named fields, create instances of it, and read its fields. It also assumes you know the basics of ownership and borrowing, and that you can build and run a program with cargo.
A named-field struct gives every field a name. Rust has two lighter forms of struct. A tuple struct has fields with positions but no names. A unit struct has no fields at all. Both are ordinary struct types. You define them with less syntax, and each is useful in a specific situation.
Tuple structs
A tuple struct looks like a struct name followed by a tuple of types.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Meters(f64);
#[derive(Debug, Clone, Copy, PartialEq)]
struct Feet(f64);
fn describe(distance: Meters) -> String {
format!("{} m", distance.0)
}
fn main() {
let m = Meters(12.5);
let f = Feet(41.0);
println!("{}", describe(m));
println!("{:?} {:?}", m, f);
let Meters(inner) = m;
println!("{inner}");
}Three things happen in this program.
- You create a value by calling the name like a function:
Meters(12.5). - You read a field by its position:
distance.0. The first field is.0, the second is.1, and so on. - You can destructure the value with a pattern that has the same shape:
let Meters(inner) = m;.
Meters and Feet both wrap an f64. They are still different types. Passing f to describe is a compile error, because describe expects a Meters. This is the main reason to use a tuple struct. It gives a plain value a distinct identity at no runtime cost, because the wrapper has the same layout as the value inside it.
Several fields
A tuple struct can have more than one field. Use it when the position of each field is obvious from context.
#[derive(Debug, PartialEq)]
struct Rgb(u8, u8, u8);
fn brightness(color: &Rgb) -> u32 {
let Rgb(r, g, b) = color;
(*r as u32 + *g as u32 + *b as u32) / 3
}
fn main() {
let orange = Rgb(255, 165, 0);
println!("{}", orange.1);
println!("{}", brightness(&orange));
match orange {
Rgb(255, _, _) => println!("full red"),
Rgb(..) => println!("some other color"),
}
}Destructuring &Rgb binds r, g, and b as references, so the function dereferences them with *. In a pattern, _ ignores one field and .. ignores all remaining fields.
Once a struct has more than two or three fields, names usually read better. color.1 tells the reader much less than color.green. If you find yourself adding a comment to explain what .2 means, switch to named fields.
The constructor is a function
The name of a tuple struct also works as a function that takes the fields and returns the struct. You can pass it wherever a function is expected.
#[derive(Debug)]
struct Meters(f64);
fn main() {
let lengths: Vec<Meters> = vec![1.0, 2.5, 4.0]
.into_iter()
.map(Meters)
.collect();
println!("{:?}", lengths);
}Here .map(Meters) is the same as .map(|x| Meters(x)). The same is true of tuple-like enum variants such as Some.
Visibility of tuple struct fields
Fields are private by default, and that includes tuple struct fields. This has a consequence that surprises many people. The constructor function is only as visible as its least visible field.
mod ids {
pub struct UserId(u32);
impl UserId {
pub fn new(raw: u32) -> Option<Self> {
if raw == 0 { None } else { Some(Self(raw)) }
}
pub fn get(&self) -> u32 {
self.0
}
}
}
use ids::UserId;
fn main() {
let id = UserId::new(7).expect("non-zero id");
println!("{}", id.get());
// let bad = UserId(0); // error: constructor is private
// println!("{}", id.0); // error: field is private
}Outside the ids module, UserId(0) does not compile, so the only way to build a UserId is new, which rejects zero. If you write pub struct UserId(pub u32);, anyone can build any value and the check is pointless. Choose the field visibility deliberately. This is the foundation of the newtype pattern, which a later chapter covers.
Unit structs
A unit struct has no fields and no parentheses.
trait Greet {
fn hello(&self) -> String;
}
struct English;
struct French;
impl Greet for English {
fn hello(&self) -> String {
String::from("Hello")
}
}
impl Greet for French {
fn hello(&self) -> String {
String::from("Bonjour")
}
}
fn greet_twice<G: Greet>(greeter: G) {
println!("{}", greeter.hello());
println!("{}", greeter.hello());
}
fn main() {
println!("{}", std::mem::size_of::<English>());
greet_twice(English);
greet_twice(French);
}The program prints 0, then the greeting twice for each language. A unit struct is a type with exactly one value, and that value is written as the bare name: English. It takes up zero bytes.
Unit structs are useful in these situations:
- Behavior without data. A type exists only to carry trait implementations, as
EnglishandFrenchdo above. The generic function picks the behavior from the type. - Marker types. A type that only labels something, for example a state in a type-level state machine.
- Placeholders. You need a type now, such as a plugin or handler, and the fields come later.
Unit struct versus empty braces
struct Marker; and struct Marker {} are not the same. The first defines both a type and a value named Marker. The second defines only a type, and you must write Marker {} to create it. Use the semicolon form when you want the bare name to be a value.
Choosing a struct form
Common errors
- Mixing up similar types.
Meters(1.0) == Feet(1.0)does not compile, becausePartialEqcompares two values of the same type. Convert explicitly, with a function or aFromimplementation. - Forgetting derives. A new tuple struct has no
Debug,Clone,Copy, orPartialEq. Add#[derive(...)]for each one you need. A wrapper aroundf64can beCopy. A wrapper aroundStringcannot. - Reading a private field from outside the module. The error is about privacy, not about the field being missing. Add a getter or make the field
pub, depending on the invariant you want to protect. - Writing
Marker()for a unit struct. That form is a tuple struct with zero fields. It compiles if you defined it that way, butstruct Marker;is the usual choice.
Exercise
You define struct Celsius(f64); and struct Kelvin(f64);, then write fn boil_check(t: Celsius) -> bool { t.0 >= 100.0 }. What happens if you call boil_check(Kelvin(373.15)), and why?
Show answer
It does not compile. Celsius and Kelvin are different types even though both wrap an f64, and Rust matches struct types by name, not by shape. You would convert explicitly, for example with a function or a From<Kelvin> for Celsius implementation.
Exercise
In a module, you write pub struct Token(String); with no other items. Can code outside the module create a Token? What single change would let it, and why might you not want that change?
Show answer
No. The constructor function is only as visible as the least visible field, and the String field is private, so Token(...) fails outside the module. Writing pub struct Token(pub String); would allow it. You might avoid that because anyone could then create a Token with any contents, which defeats a check or invariant you want a constructor function to enforce.
Exercise
What is the difference between struct Marker; and struct Marker {}, and what does std::mem::size_of::<Marker>() return for each?
Show answer
struct Marker; defines a type and also a value named Marker. struct Marker {} defines only a type, so you must write Marker {} to create a value. Both have no fields, so size_of returns 0 for each.