Sub topic 3
Owned Fields and Struct Design Patterns
Assume you know Rust ownership, borrowing, functions, and how to run a Cargo program. This chapter focuses on how those ideas shape struct interfaces.
Owned fields and moves out of structs
A struct owns a field when the field has its own value, such as a String. Moving that field transfers ownership. Afterward, the original field cannot be used.
#[derive(Debug)]
struct User {
name: String,
}
fn main() {
let user = User {
name: String::from("Ada"),
};
let name = user.name;
println!("{name}");
}The user.name expression moves the String. Borrow with &user.name when the value must remain in the struct.
Privacy and encapsulation
A private field can only be accessed inside its module. Public methods can protect invariants, which are rules that must always remain true.
mod account {
pub struct Account {
balance: u64,
}
impl Account {
pub fn new() -> Self {
Self { balance: 0 }
}
pub fn deposit(&mut self, amount: u64) {
self.balance += amount;
}
pub fn balance(&self) -> u64 {
self.balance
}
}
}
fn main() {
let mut account = account::Account::new();
account.deposit(25);
println!("{}", account.balance());
}Implementing `Display`
Display defines user-facing formatting. Implement it when your type should work with {} in println!.
use std::fmt;
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn main() {
println!("{}", Point { x: 2, y: 3 });
}Generic structs and methods
A generic struct works with several types. Bounds restrict which operations a method may use.
struct Pair<T> {
first: T,
second: T,
}
impl<T: PartialOrd + Copy> Pair<T> {
fn larger(&self) -> T {
if self.first > self.second { self.first } else { self.second }
}
}Structs that borrow data
A reference field needs a lifetime parameter. The lifetime states that the struct cannot outlive the borrowed text.
struct Excerpt<'a> {
text: &'a str,
}The builder pattern
A builder collects configuration before creating the final value. By-value methods can return the builder for chaining.
struct Server {
port: u16,
}
struct Builder {
port: u16,
}
impl Builder {
fn new() -> Self { Self { port: 80 } }
fn port(mut self, port: u16) -> Self { self.port = port; self }
fn build(self) -> Server { Server { port: self.port } }
}The newtype pattern
A tuple struct creates a distinct type around an existing type. This prevents accidentally mixing values with the same underlying type.
struct Meters(f64);
fn main() {
let distance = Meters(12.5);
println!("{}", distance.0);
}Exercise
Why would a method take &self instead of self?
Show answer
It takes &self when it only needs to read the struct and should leave ownership with the caller.