Methods are functions defined within the context of a struct (or enum/trait).
struct Circle {
radius: f64,
}
impl Circle {
// Associated function (no self) - like a constructor
fn new(radius: f64) -> Self {
Circle { radius }
}
// Method (takes &self)
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
// Method that modifies self
fn grow(&mut self, amount: f64) {
self.radius += amount;
}
}| Syntax | Meaning |
|---|---|
self | Takes ownership |
&self | Immutable borrow |
&mut self | Mutable borrow |
Self (capital S) is an alias for the type being implemented. self (lowercase) is the instance.
let mut c = Circle::new(5.0); // associated function
let a = c.area(); // method with &self
c.grow(2.0); // method with &mut selfCreate a Rectangle with:
new(width, height) - associated functionarea(&self) - returns width × heightis_square(&self) - returns true if width == heightRectangle::new(5, 5).area() → 25Rectangle::new(5, 5).is_square() → trueRectangle::new(5, 3).is_square() → falseimpl Rectangle {
fn new(width: u32, height: u32) -> Self {
Self { width, height }
}
fn area(&self) -> u32 {
self.width * self.height
}
}