Model records with structs
Quick answer
A struct groups named fields into a new type. Use it when several values describe one entity, such as a product with a name and quantity. Field names make the model more readable than positional tuples.
Declare, construct and access
Declare struct Product { name: String, quantity: u32 } outside main. Create an instance with Product { name: ..., quantity: ... }, supplying every field. Use the dot to read fields. To change an ordinary field, the instance binding must be mutable. A struct containing a String owns it; moving that String out can partially move the record.
struct Product { name: String, quantity: u32 }fn main() { let product = Product { name: String::from("Pen"), quantity: 3 }; println!("{}: {}", product.name, product.quantity);}Expected stdout (not executed):
Pen: 3Named fields communicate the meaning of each value.
struct Stock { quantity: u32 }fn main() { let mut stock = Stock { quantity: 5 }; stock.quantity += 2; println!("{}", stock.quantity);}Expected stdout (not executed):
7Mutability belongs to the binding here, not to an individual field declaration.
Common mistake
Do not omit a field when constructing a struct unless you use an applicable struct update expression.
Try it yourself
Model a book with title and page count. Construct two books and print their named fields.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Model records with structs — practice quiz
Choose one answer per question, then review the explanation.
Which syntax reads the quantity field of a Product instance p?
What is required to directly assign an ordinary field of a locally owned struct?
After moving a String field out of a struct with no custom Drop, can its remaining Copy field still be read?