Concept Flow - Unit-like structs
Define unit-like struct
Create instance
Use instance (no data inside)
Pass or return instance
End
Unit-like structs have no fields and act like markers or flags. You define, create, and use them without storing data.
struct Marker;
fn main() {
let m = Marker;
println!("Instance created: {}", std::any::type_name::<Marker>());
}| Step | Action | Code Line | Result/State |
|---|---|---|---|
| 1 | Define unit-like struct Marker | struct Marker; | Marker type exists, no data fields |
| 2 | Enter main function | fn main() { | Ready to create instance |
| 3 | Create instance m of Marker | let m = Marker; | m is instance of Marker, no data inside |
| 4 | Print type name of m | println!("Instance created: {}", std::any::type_name::<Marker>()); | Output: Instance created: Marker |
| 5 | End main function | } | Program ends |
| Variable | Start | After Step 3 | Final |
|---|---|---|---|
| m | undefined | Marker instance (no data) | Marker instance (no data) |
Unit-like structs have no fields and are defined with a semicolon after the name. Create instances by writing the struct name without parentheses or braces. They hold no data and act as markers or flags. Useful for type safety and traits. Example: struct Marker; let m = Marker;
Marker in Rust?struct Marker;struct Flag;
impl Flag {
fn is_set(&self) -> bool {
true
}
}
fn main() {
let f = Flag;
println!("{}", f.is_set());
}is_set that always returns true.f of Flag and call f.is_set(), which returns true, printed as "true".struct Label;
fn main() {
let l = Label();
println!("Label created");
}Label() which is invalid; it should be Label.struct Marker;
impl Marker {
fn label(&self) -> &'static str {
"Unit Marker"
}
}
fn main() {
let markers = vec![Marker, Marker];
for m in markers {
println!("{}", m.label());
}
}Pass the test and this pattern moves unknown