Sub topic 2
Adding Behavior with `impl` Blocks
Assume basic Rust syntax, ownership, borrowing, and Cargo. An impl block attaches functions and methods to a struct. This keeps data and the operations that use it together.
Associated Functions and Constructors
An associated function belongs to a type but does not receive an instance. Its first parameter is not self. Constructors commonly use the name new:
#[derive(Debug, Clone, PartialEq, Default)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn new(width: u32, height: u32) -> Self {
Self { width, height }
}
fn square(size: u32) -> Self {
Self::new(size, size)
}
fn area(&self) -> u32 {
self.width * self.height
}
fn scale(&mut self, factor: u32) {
self.width *= factor;
self.height *= factor;
}
fn into_dimensions(self) -> (u32, u32) {
(self.width, self.height)
}
}
fn main() {
let mut rectangle = Rectangle::new(3, 4);
println!("area = {}", rectangle.area());
rectangle.scale(2);
println!("{rectangle:?}");
let square = Rectangle::square(5);
println!("square area = {}", square.area());
let dimensions = rectangle.into_dimensions();
println!("{dimensions:?}");
}Call associated functions with Type::function(), such as Rectangle::new(3, 4).
Methods and Receivers
A method receives an instance through a self parameter:
&selfborrows the instance for reading.&mut selfmutably borrows it for changing.selftakes ownership and consumes the instance.
Use self when the method transforms or permanently takes the value. After into_dimensions runs, rectangle cannot be used again.
How Method Calls Resolve Receivers
Rust automatically adds borrowing or dereferencing when a method call matches the receiver. Therefore, rectangle.area() can call a method declared as fn area(&self). The variable must still have the required mutability for &mut self.
Deriving Common Traits
#[derive(...)] asks the compiler to generate implementations. Debug enables {:?} formatting, Clone enables .clone(), PartialEq enables ==, and Default provides Rectangle::default() when every field has a default.
Exercise
Which receiver should a method use if it only calculates a value from a struct?
Show answer
Use &self, because the method needs shared read-only access and should not consume or modify the struct.