Topic
Structs
A struct defines a custom type by naming a group of fields, each with its own type. Once defined, you instantiate it with real data. Rust lets you update fields on a mutable instance, copy most fields from another instance with struct update syntax, or create simpler tuple structs that use positions instead of names. Structs are the building block for data records.
Quick Reference
| Concept | What it means |
|---|---|
| struct | A custom compound type that groups values of different types under named fields. |
| Dot notation | Access a field with instance.field_name. |
| let mut | The whole struct must be mutable to change any field. |
| Shorthand | When a variable name matches a field name, write it once: field_name instead of field_name: field_name. |
| ..instance | Struct update syntax: copy all remaining fields from another instance. |
| Tuple struct | A named tuple: struct Color(i32, i32, i32); |
| Unit-like struct | A struct with no fields, mainly used with traits. |
| #[derive(Debug)] | An attribute that lets you print a struct with {:?}. |
| Term | What it means | When you use it |
|---|---|---|
| struct | A custom compound type that groups values of different types under named fields | When defining a reusable data record |
| Dot notation | Access a field with instance.field_name | When reading or writing a single field on a struct instance |
| let mut | The whole struct must be mutable to change any field | When a field's value needs to change after the instance is created |
| Shorthand | Write the field name once when a variable matches the field name | Inside functions that build struct instances from matching parameters |
| ..instance | Struct update syntax: copy all remaining fields from another instance | When creating a copy of a struct with only a few fields changed |
| Tuple struct | A named tuple: struct Color(i32, i32, i32); | When you want a distinct type but don't need named fields |
| Unit-like struct | A struct with no fields, mainly used with traits | When you need a marker type that carries no stored data |
| #[derive(Debug)] | An attribute that lets you print a struct with {:?} | When debugging or printing a struct value in the Playground |
| Partial move | Moving one field out of a struct invalidates the whole struct afterward | When you move a field out - be careful, the struct is no longer usable |