Skip to content

Methods and impl

Associated functions, methods, receiver forms, builder chains, and destructors.

impl Point:
def move_x(self: mut view Point, dx: i32) -> None:
self.x = self.x + dx
return None

impl Type: opens a block where associated functions and methods live. There is no separate static keyword: a function without a self parameter is associated; with one, it’s a method.

ReceiverMeaning
self: TypeMethod takes the receiver by value (consuming)
self: view TypeMethod takes a shared borrow
self: mut view TypeMethod takes a mutable borrow
self: SelfInside an impl, Self is the concrete impl receiver type: most useful for owned builder chains
impl Box[T]:
def value(self: view Box[T]) -> view T:
return view self.value

Methods may use the impl’s type parameters after substitution. Method-level type parameters (def method[T](...)) are reserved for a later milestone.

Owned builder-style chains work when each chained method takes self: Type by value and returns the next owned struct value:

let server = Server.builder()
.host("127.0.0.1")
.port(3000)
.workers(4)
.build()

Borrowed-receiver chaining from temporaries is not yet supported. Bind the value to a local before calling view self / mut view self methods.

Consuming builder methods may move direct owned storage fields (String, ByteBuf, List[T]) out of self when the containing builder type does not define drop.

A destructor is exactly:

def drop(self: mut view Type) -> None:
# cleanup
return None

Destructors cannot be called by user code: the compiler inserts calls at scope exit. They run before the storage of self is reclaimed.

See also Resources and defer for use ... cleanup ... blocks, which complement destructors when you want explicit cleanup ordering.