Sub topic 1
Defining a struct
Prerequisites
You should know basic Rust variables, functions, primitive types, ownership, borrowing, and how to run a Cargo project.
Defining a struct
A struct is a custom type that groups related values called fields. Each field has a name and a type.
#[derive(Debug, Clone)]
struct Rectangle {
width: u32,
height: u32,
}Rectangle has two owned integer fields. The Debug and Clone traits are derived so values can be printed with {:?} and copied with .clone().
Creating instances
Create an instance by naming the struct and assigning every field:
let first = Rectangle {
width: 30,
height: 20,
};Field initialization shorthand lets you reuse variables with the same names:
let width = 10;
let height = 5;
let second = Rectangle { width, height };A struct value owns its fields according to their types. For example, a String field owns its text, while a &str field borrows text.
flowchart TD
A[Rectangle value] --> B[width: 30]
A --> C[height: 20]Reading and changing fields
Use the dot operator to read a field. The instance must be mutable before you change one:
fn main() {
let mut rect = Rectangle {
width: 30,
height: 20,
};
println!("width = {}", rect.width);
rect.width = 40;
println!("{:?}", rect);
}Mutability belongs to the binding, not to individual fields. An immutable binding prevents all field changes.
Building from another instance with struct update syntax
Struct update syntax copies or moves the remaining fields from an existing instance:
let base = Rectangle {
width: 30,
height: 20,
};
let taller = Rectangle {
height: 50,
..base
};Here, taller.width comes from base. Because u32 is Copy, base.width remains usable. With non-Copy fields such as String, the update may move fields and make the original value partly unavailable.
Tuple structs and unit structs
A tuple struct has unnamed fields, accessed by position:
struct Meters(u32);
let distance = Meters(12);
println!("{}", distance.0);A unit struct has no fields. It is useful as a marker type:
struct LoggedIn;
let _status = LoggedIn;Exercise
What must change before rect.width = 40 can compile?
Show answer
The rect binding must be declared with let mut rect.