Methods
Methods are functions attached to a type, defined in impl blocks.
impl blocks
Section titled “impl blocks”An impl block groups methods for a type:
struct Rectangle { width: float64, height: float64,}
impl Rectangle { fn area(self) -> float64 { self.width * self.height }
fn scale(self: mut Ref<Rectangle>, factor: float64) { self.width *= factor self.height *= factor }}Methods are called with dot notation:
let mut rect = Rectangle { width: 10.0, height: 5.0,}
let before = rect.area()50.0rect.scale(2.0)let after = rect.area()200.0A type can have multiple impl blocks.
Receivers
Section titled “Receivers”A method on an instance takes a self parameter, called the receiver.
A value receiver reads a copy:
impl Rectangle {copy of Rectangle instance fn area(self: Rectangle) -> float64 { self.width * self.height }}A Ref receiver reads the original:
impl Rectangle {read-only pointer to Rectangle instance fn perimeter(self: Ref<Rectangle>) -> float64 { 2.0 * (self.width + self.height) }}A mut Ref receiver writes to the original:
impl Rectangle {writable pointer to Rectangle instance fn scale(self: mut Ref<Rectangle>, factor: float64) { self.width *= factor self.height *= factor }}Prefer the value receiver for a small struct, and Ref for a large one, where the copy
is costly. See Go’s guidance on
receiver types.
A value receiver may omit the type:
impl Rectangle {same as self: Rectangle fn area(self) -> float64 { self.width * self.height }}Instead of spelling out the type, a method may use Self for the type being implemented:
struct CoordinatePair<T> { first: T, second: T,}
impl<T> CoordinatePair<T> {same as CoordinatePair<T> fn swap(self: mut Ref<Self>) { let held = self.first self.first = self.second self.second = held }same as CoordinatePair<T> fn swapped(self) -> Self { CoordinatePair { first: self.second, second: self.first } }}Associated functions
Section titled “Associated functions”A method without self is an associated function. It belongs to the type, not to an instance:
impl Rectangle { fn square(size: float64) -> Rectangle { Rectangle { width: size, height: size } }}
let squared = Rectangle.square(5.0)called on the type itself, not on an instanceGeneric methods
Section titled “Generic methods”A method can define type parameters of its own:
impl<T> Option<T> {T is the type inside Option fn map<U>(self, f: fn(T) -> U) -> Option<U> {U is what f turns T into match self { Some(value) => Some(f(value)), None => None, } }}let count = Some(42)let label = count.map(|n| f"{n}")Option<string>