Rust Tutorial: Structs
Define custom data types, add methods with impl, and use associated functions as constructors.
Custom data types
A struct groups related fields under one name. Methods are functions attached to that struct via `impl`.
What you'll learn in this Rust structs tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 20 minutes.
- Define a struct — Declare a struct with named fields. Create instances with field names.
- Mutable struct instance — To change a field, the variable must be `mut`.
- Debug formatting — `#[derive(Debug)]` generates a debug print. Use `{:?}` or `{:#?}`.
- Methods with impl — Methods live in an `impl` block. The first parameter `&self` refers to the instance.
- Mutating methods — Use `&mut self` to modify the struct in a method.
- Associated functions — Associated functions do not take `self`. Call them with `TypeName::function()`.
- Struct update syntax — Reuse fields from an existing struct with `..existing`:
- Tuple structs — Tuple structs wrap values without field names. Access via `.0`, `.1`, etc.
Rust Structs concepts covered
- Custom data types