Methods and impl
Associated functions, methods, receiver forms, builder chains, and destructors.
impl blocks
Section titled “impl blocks”impl Point: def move_x(self: mut view Point, dx: i32) -> None: self.x = self.x + dx return Noneimpl 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.
Receiver forms
Section titled “Receiver forms”| Receiver | Meaning |
|---|---|
self: Type | Method takes the receiver by value (consuming) |
self: view Type | Method takes a shared borrow |
self: mut view Type | Method takes a mutable borrow |
self: Self | Inside an impl, Self is the concrete impl receiver type: most useful for owned builder chains |
Generic impls
Section titled “Generic impls”impl Box[T]: def value(self: view Box[T]) -> view T: return view self.valueMethods may use the impl’s type parameters after substitution. Method-level type parameters (def method[T](...)) are reserved for a later milestone.
Builder chains
Section titled “Builder chains”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.
Destructors
Section titled “Destructors”A destructor is exactly:
def drop(self: mut view Type) -> None: # cleanup return NoneDestructors 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.