Unit-like struct
- Rust course
- Beginner
- Lesson 68/115
- 4 min
Get to know the fieldless unit-like struct.
Unit-like structs
A struct with no fields is called a unit-like struct. It holds no data and takes 0 bytes in memory; it's used to carry a behaviour (trait) or to mark a state at the type level:
struct Sessiz;
let s = Sessiz;
println!("{}", std::mem::size_of::<Sessiz>()); // 0The instance is created with just the name, without braces.
Marker types
Unit-like structs work as "labels" in the type system. For example, whether a connection is open or closed can be shown with a type instead of a runtime bool:
struct Acik;
struct Kapali;
struct Kapi<Durum> { ad: String, durum: Durum }
let k = Kapi { ad: String::from("giriş"), durum: Kapali };You'll see this "typestate" pattern with generics in later lessons. For now, what matters is: no fields means no cost.
Practice Measure the sizes
Define struct Sessiz; and struct Renk(u8, u8, u8);. Print the size of both with std::mem::size_of, separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
struct Sessiz;
struct Renk(u8, u8, u8);
fn main() {
println!("{} {}", std::mem::size_of::<Sessiz>(), std::mem::size_of::<Renk>());
}Expected output
0 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>std::mem::size_of::<Renk>()</code>? (<code>struct Renk(u8, u8, u8);</code>)
- 3 Correct answer
- 0
- 8
- 24
Explanation: Three u8 fields are 1 byte each; no padding is needed.
2 A struct without fields
struct Sessiz____
let s = Sessiz;
struct Sessiz;
let s = Sessiz;
Explanation: A unit-like struct ends with a semicolon; no braces are needed.
3 Struct and its size
| Term | Meaning |
|---|---|
struct Sessiz; |
0 bytes |
struct Renk(u8, u8, u8); |
3 bytes |
struct Tek(u32); |
4 bytes |
struct Cift(u64, u64); |
16 bytes |