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
ConceptWhat it means
structA custom compound type that groups values of different types under named fields.
Dot notationAccess a field with instance.field_name.
let mutThe whole struct must be mutable to change any field.
ShorthandWhen a variable name matches a field name, write it once: field_name instead of field_name: field_name.
..instanceStruct update syntax: copy all remaining fields from another instance.
Tuple structA named tuple: struct Color(i32, i32, i32);
Unit-like structA struct with no fields, mainly used with traits.
#[derive(Debug)]An attribute that lets you print a struct with {:?}.
TermWhat it meansWhen you use it
structA custom compound type that groups values of different types under named fieldsWhen defining a reusable data record
Dot notationAccess a field with instance.field_nameWhen reading or writing a single field on a struct instance
let mutThe whole struct must be mutable to change any fieldWhen a field's value needs to change after the instance is created
ShorthandWrite the field name once when a variable matches the field nameInside functions that build struct instances from matching parameters
..instanceStruct update syntax: copy all remaining fields from another instanceWhen creating a copy of a struct with only a few fields changed
Tuple structA named tuple: struct Color(i32, i32, i32);When you want a distinct type but don't need named fields
Unit-like structA struct with no fields, mainly used with traitsWhen 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 moveMoving one field out of a struct invalidates the whole struct afterwardWhen you move a field out - be careful, the struct is no longer usable