In this tutorial, you’ll learn about tuple struct and unit structs, which are alternative struct forms for different use cases.
Tuple Structs #
Tuple structs look like tuples, but they have a name and act as a distinct type.
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
fn main() {
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
// Access fields by index
println!("Black RGB: {}, {}, {}", black.0, black.1, black.2);
println!("Origin: ({}, {}, {})", origin.0, origin.1, origin.2);
}
Code language: Rust (rust)Even though Color and Point have the same structure ((i32, i32, i32)), they are different types.
This prevents mixing up values that have the same fields but different meaning.
Use case: when you want a simple wrapper type with meaning, but don’t need named fields.
Unit Structs #
A unit struct has no fields — it’s just a type by itself.
struct Marker;
fn main() {
let _m = Marker; // no fields to initialize
}
Code language: Rust (rust)They are useful for:
- Type-level markers (e.g., phantom types in generics).
- Traits implementation where you don’t need data.
Example:
struct Logger;
impl Logger {
fn log(&self, msg: &str) {
println!("[LOG] {}", msg);
}
}
fn main() {
let logger = Logger;
logger.log("Hello, world!");
}
Code language: Rust (rust)Here, Logger doesn’t store anything, but it gives us a namespace for behavior.
Named Struct vs. Tuple Struct vs. Unit Struct #
| Struct Type | Example | When to Use |
|---|---|---|
| Named Struct | struct Rectangle { width, height } | When you want clear, descriptive field names. |
| Tuple Struct | struct Point(i32, i32, i32) | When fields don’t need names, but you want a distinct type. |
| Unit Struct | struct Marker; | When you only care about the type, not the data. |
Summary #
- Tuple structs: like tuples, but with type safety and meaning.
- Unit structs: empty types, useful for markers and traits.
- These give you flexibility depending on how much structure you need.
Was this Helpful ?