Skip to content

Methods

Methods are functions attached to a type, defined in 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.0
rect.scale(2.0)
let after = rect.area()200.0

A type can have multiple impl blocks.

A method on an instance takes a self parameter, called the receiver.

A value receiver reads a copy:

impl Rectangle {
fn area(self: Rectangle) -> float64 {
copy of Rectangle instance
self.width * self.height
}
}

A Ref receiver reads the original:

impl Rectangle {
fn perimeter(self: Ref<Rectangle>) -> float64 {
read-only pointer to Rectangle instance
2.0 * (self.width + self.height)
}
}

A mut Ref receiver writes to the original:

impl Rectangle {
fn scale(self: mut Ref<Rectangle>, factor: float64) {
writable pointer to Rectangle instance
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 {
fn area(self) -> float64 {
same as self: Rectangle
self.width * self.height
}
}

Calling a method never needs an explicit & or .*, because Lisette auto-adds them as needed.

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 instance

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>