Level 1 · Foundations· Lesson 6 of 10 · 20 min
Structs and methods
Defining your own data types, attaching behaviour with impl blocks, and deriving common traits.
Defining a struct
A struct groups named fields into one type.
#[derive(Debug)]
struct User {
name: String,
age: u32,
active: bool,
}
fn main() {
let mut user = User {
name: String::from("Ada"),
age: 36,
active: true,
};
user.age += 1;
println!("{} is {}", user.name, user.age);
println!("{user:?}");
println!("{user:#?}"); // pretty-printed
}
Mutability belongs to the binding, not to individual fields: let mut user makes every field assignable.
#[derive(Debug)] asks the compiler to generate the code that makes {:?} work. You will add it to nearly every type you write.
Shorthand and update syntax
#[derive(Debug, Clone)]
struct Config {
host: String,
port: u16,
verbose: bool,
}
fn main() {
let host = String::from("localhost");
let port = 8080;
let base = Config { host, port, verbose: false }; // field-init shorthand
let noisy = Config { verbose: true, ..base.clone() }; // take the rest from another value
println!("{base:?}\n{noisy:?}");
}
Tuple structs and unit structs
struct Metres(f64);
struct Seconds(f64);
struct Marker;
fn speed(d: Metres, t: Seconds) -> f64 {
d.0 / t.0
}
fn main() {
let _m = Marker;
println!("{} m/s", speed(Metres(100.0), Seconds(9.58)));
// speed(Seconds(9.58), Metres(100.0)); // ❌ would not compile: arguments swapped
}
Wrapping a primitive in a tuple struct is the newtype pattern. It costs nothing at runtime and stops you mixing up values that share a representation but not a meaning.
Methods
Behaviour goes in an impl block.
#[derive(Debug)]
struct Rectangle {
width: f64,
height: f64,
}
impl Rectangle {
// Associated function (no self): used as a constructor.
fn new(width: f64, height: f64) -> Self {
Self { width, height }
}
fn square(side: f64) -> Self {
Self::new(side, side)
}
// Borrows immutably: reads only.
fn area(&self) -> f64 {
self.width * self.height
}
// Borrows mutably: changes the value in place.
fn scale(&mut self, factor: f64) {
self.width *= factor;
self.height *= factor;
}
// Takes ownership: consumes the value.
fn into_square(self) -> Rectangle {
let side = self.width.max(self.height);
Rectangle::square(side)
}
}
fn main() {
let mut r = Rectangle::new(3.0, 4.0);
println!("area {}", r.area());
r.scale(2.0);
println!("{r:?}");
let s = r.into_square(); // r is moved; using it after this is an error
println!("{s:?}");
}
The receiver tells the caller what the method may do:
| Receiver | Meaning | Use when |
|---|---|---|
&self |
shared borrow | reading — the common case |
&mut self |
exclusive borrow | modifying in place |
self |
takes ownership | transforming into something else, or consuming |
Self (capital S) is an alias for the type being implemented. Rust has no special constructor syntax; new is only a convention.
When you write r.area(), Rust automatically borrows as needed — it is the same as Rectangle::area(&r).
Ownership inside structs
A struct owns its fields. When the struct is dropped, the fields are dropped. Moving a field out of a struct leaves the struct partially moved:
struct Article {
title: String,
body: String,
}
fn main() {
let a = Article {
title: String::from("Ownership"),
body: String::from("…"),
};
let title = a.title; // moves the title out
println!("{title}");
println!("{}", a.body); // other fields are still usable
// let b = a; // ❌ a is partially moved
}
To store a reference in a struct you need lifetime annotations, covered in Level 2. Until then, have structs own their data (String, not &str).
Exercises
- Define
struct Circle { radius: f64 }withnew,areaandcircumferencemethods (usestd::f64::consts::PI). - Define a
Counterwith acount: u32field,new(),increment(&mut self), andget(&self) -> u32. - Add
fn can_hold(&self, other: &Rectangle) -> booltoRectangle.
Solution to 3
struct Rectangle { width: f64, height: f64 }
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
fn main() {
let big = Rectangle { width: 8.0, height: 6.0 };
let small = Rectangle { width: 3.0, height: 2.0 };
println!("{} {}", big.can_hold(&small), small.can_hold(&big));
}
Check your understanding
Pick an answer to see the explanation.
1.What does
&selfmean in a method signature?2.How do you call an associated function such as
newthat has noselfparameter?3.What does
#[derive(Debug)]give you?