A receiver method is a function that lives inside a struct.
You create a struct, then create a function that can only be called from instances of those structs.
Its first parameter is named this:
Vector2 = |
x Float,
y Float,
|
length_squared |this Vector2| -> Float:
return this.x * this.x + this.y * this.y
;
vector = Vector2(3.0, 4.0)
length = vector.length_squared()
The method is written as a normal top-level function in the same file as the type.
Call it with value.method(), not method(value).
Methods exist as a helpful to organise code. They belong to the struct, so can only be called from instances of that type and are passed around with that type.
A receiver method is a top-level function whose first parameter is named this.
Vector2 = |
x Float,
y Float,
|
length_squared |this Vector2| -> Float:
return this.x * this.x + this.y * this.y
;
vector = Vector2(3.0, 4.0)
length = vector.length_squared()
Receiver declaration
this must be the first parameter.- A signature may contain exactly one
this parameter. this T is a shared receiver.this ~T is a mutable receiver.this is reserved for receiver declarations and the receiver method body.- A receiver method is called only with receiver syntax.
- Calling it as
method(value, ...) is invalid.
Supported receiver ownership
A source-authored receiver method belongs to a user-defined struct or choice declared in the same source file.
Aligned declaration-site generic nominal receivers are supported when the method belongs to that generic type declaration.
Source-authored receiver methods are rejected for:
- builtin scalars
- imported source types
- dependency package types
- external opaque types
- nominal types declared in another file
Use a free function for a type owned elsewhere.
Compiler-owned collection operations and builder-owned builtin operations are not user extension methods.
Constants and receiver methods
A struct instance folded into a constant becomes a data-only const record. Its folded fields remain available under the constant rules, but runtime receiver methods are not available on the const record itself.
Use one projected field when runtime code needs the value. See Const records for the const-record contract.
Visibility
Receiver-method visibility follows receiver-type visibility.
- A method becomes callable wherever its receiver type is visible.
- Methods are not imported, aliased or re-exported independently.
- Namespace imports may expose the receiver type, but its methods are not namespace fields.
- A module public surface exposes same-file receiver methods when it exposes the receiver type.
- A field and receiver method on the same type cannot use the same name.