Docs · Language
Methods and dispatch
A method is a free-standing fn with a receiver written before its name. A
type's definition lists fields and nothing else: which methods a call can reach
depends on where the call is written and on how its value's type arrived there.
This page states the receiver forms, how a call finds a method (scope first,
then the type's pocket), method imports, overload selection, interfaces, and
calls on a union. Guides
04, Functions and closures,
12, Interfaces, and
14, Modules and packages
introduce them.
Receiver forms
| Receiver | Example | The method gets |
|---|---|---|
| value | fn (p: Point) length() | a copy; changes never reach the caller |
| writable pointer | fn (p: *mut Point) move() | the original's address; may change it |
| read-only pointer | fn (p: *con Point) show() | the original's address, for reading |
| type | fn (Point) origin() | no value; called on the type, Point.origin() |
A pointer receiver states its mutability, *mut or *con, as every pointer
type does (memory model). A method may be declared
on any type: a struct, an enum, a primitive, a union, a generic instance, an
array pointer, an interface. Inside a pointer-receiver method, field access
dereferences for you: p.x, not (*p).x.
import { println } from "@fmt"
struct Point { x: i32, y: i32 }
fn (Point) origin() Point { return Point{ x: 0, y: 0 } }
fn (p: Point) sum() i32 { return p.x + p.y }
fn (p: *mut Point) move(dx: i32) { p.x += dx }
fn main() !u8 {
mut p = Point.origin()
p.move(5)
println(p.sum()) // prints 5
return Ok(0)
}Receiver adaptation
An instance method adapts across one level of *mut or *con around its
receiver's type. Type-receiver methods do not adapt
(static and instance calls).
| Declared receiver | Call subject | The call passes | Changes the caller? |
|---|---|---|---|
T | a value of T | a copy | no |
T | *mut T or *con T | a copy of the pointee | no |
T | *c_ptr T | a copy of the pointee | no |
*mut T | a writable place of T | its address, as *mut T | yes |
*mut T | a *mut T | the pointer | yes |
*mut T | a con binding, a parameter, or a *con T | not a candidate | |
*con T | a value of T | its address, as *con T | no |
*con T | a *mut T or *con T | the pointer, as *con T | no |
*mut T or *con T | a *c_ptr T, or a place reached through one | not a candidate |
A writable place is a mut binding, a field or element of one reached without
crossing a pointer, or any place reached through a *mut pointer (p.field
with p: *mut T). A value in a con binding or a parameter is not writable,
and neither is anything reached through a *con pointer, even one held in a
mut binding.
A C pointer is looked through like a strict one, but the address of a place reached through it is a C pointer too (guide 15). So neither a pointer-receiver method nor a method of an interface (whose conversion takes the subject's address) is callable through one.
When several same-name methods apply, the call picks:
- the one whose receiver matches the subject exactly;
- else a pointer adaptation (taking the address, or
*mutto*con) over a copy; - else the ordinary overload rules (overload selection).
import { println } from "@fmt"
struct Counter { count: i32 }
fn (c: Counter) kind() [*con]u8 { return "value" }
fn (c: *mut Counter) kind() [*con]u8 { return "*mut" }
fn (c: *con Counter) kind() [*con]u8 { return "*con" }
fn main() !u8 {
mut c = Counter{ count: 0 }
con readOnly: *con Counter = &c
println(c.kind()) // prints value
println(readOnly.kind()) // prints *con
return Ok(0)
}A *mut method on a subject that is not writable is reported as a missing
method, with a note that it is defined for *mut Point but not callable on an
immutable value:
struct Point { x: i32 }
fn (p: *mut Point) bump() { p.x += 1 }
fn main() !u8 {
con p = Point{ x: 1 }
p.bump() // error: cannot call "bump" here
return Ok(0)
}Static vs instance calls
A type receiver declares a static method, called on the type: Point.origin().
The two call shapes do not cross. A static method is not callable through a
value, and an instance method is not callable through its type with the
receiver as an argument:
struct Point { x: i32 }
fn (Point) origin() Point { return Point{ x: 0 } }
fn main() !u8 {
con p = Point{ x: 3 }
con o = p.origin() // error: type Point has no method "origin"
return Ok(0)
}A static method named through its type without a call is a function value,
like a function's name. It can be bound, passed to a fn(...) parameter, and
stored in a fn(...) field. That holds for a generic type's instance too
(Cell(i32).of). An instance method is not a value, and & does not apply to
either kind.
import { println } from "@fmt"
struct Price { cents: i32 }
fn (Price) of(cents: i32) Price { return Price{ cents: cents } }
fn total(make: fn(i32) Price, cents: i32) i32 {
return make(cents).cents
}
fn main() !u8 {
println(total(Price.of, 250)) // prints 250
return Ok(0)
}struct Price { cents: i32 }
fn (p: Price) doubled() i32 { return p.cents * 2 }
fn main() !u8 {
con p = Price{ cents: 1 }
con f = p.doubled // error: doubled is a method, which is called
return Ok(0)
}Method sets are scope-determined
A method is not part of its type. Anyone can declare a method on any type, including a primitive or a type from another package, and the method is a declaration in the scope where it is written:
import { println } from "@fmt"
fn (n: i32) doubled() i32 { return n * 2 }
fn main() !u8 {
con count: i32 = 7
println(count.doubled()) // prints 14
return Ok(0)
}A call value.name(...) looks for name in this order:
- Scope at the call. The enclosing blocks from the innermost outward, then the file's own declarations, then the methods the file imports by method item (importing methods), the later of two imports first, then the builtin scope.
- The pocket of the value's type, as the value carries it (scope and the pocket).
The first place that has a method of that name with a fitting signature decides. Nothing is global: a method reaches a call only from a scope that encloses the call or from a pocket the value carries. Operators (operators) and conversions to an interface (interfaces) look up their methods the same way.
Scope and the pocket
A type's pocket holds the methods that travel with the type from file to file through imports and re-exports.
What goes into a pocket
- A method goes into the pocket when it is defined in the same scope as the type's binding in that file: beside the type's declaration, beside a
typebinding of it, or beside the file's import of it. - Only an exported method goes into the pocket for the next importer. A method without
exportis usable only within the scope it is declared in, even when it is declared beside its type. - A method imported into a file by a method item is callable there by scope and is not in any pocket.
- A method defined in a scope nested below the type's binding (inside a function body) is scope-only.
- A primitive type's binding stands at each file's top level, so
export fn (n: i32) twice()at file level is beside that file'si32.
The pocket grows with each export. A file that imports a type, exports more methods beside the import, and re-exports the type hands out a type carrying everything it imported plus what it added:
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
export fn (r: Rect) area() i32 {
return r.width * r.height
}
// file: measure.vyi
import { Rect } from "./rect"
export fn (r: Rect) perimeter() i32 {
return 2 * (r.width + r.height)
}
export { Rect }
// file: main.vyi
import { println } from "@fmt"
import { Rect } from "./measure"
fn main() !u8 {
con r = Rect{ width: 2, height: 3 }
println(r.area()) // prints 6
println(r.perimeter()) // prints 10
return Ok(0)
}A file that imports Rect from rect.vyi gets only area. A file importing
from further back along the path sees nothing a later file added, and two files
that each import Rect from rect.vyi and add methods hand out two pockets
that do not see each other. A type has no single pocket: each binding of it has
its own. A file that imports one type twice, under two names, holds two
bindings and two pockets.
Renaming an import keeps the pocket: after `import { Rect: Tile } from
"./measure", a Tile has area and perimeter`.
A method without export does not reach an importer:
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
// file: measure.vyi
import { Rect } from "./rect"
fn (r: Rect) perimeter() i32 {
return 2 * (r.width + r.height)
}
export { Rect }
// file: main.vyi
import { Rect } from "./measure"
fn main() !u8 {
con r = Rect{ width: 2, height: 3 }
con edge = r.perimeter() // error: type Rect has no method "perimeter"
return Ok(0)
}All versions of a type are one type: the same fields, layout, and identity in every file, and a value passes freely between them. Only the methods a call can find differ.
A value carries its pocket
A value carries the pocket of the binding its written type names: the annotation, field, payload, element, or result type that gives it its type. A value whose type is written nowhere, such as a literal, carries the pocket its type has in the file where the value is made. So a value returned from another file brings its pocket along, with nothing else imported:
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
export fn (r: Rect) area() i32 {
return r.width * r.height
}
export fn square(side: i32) Rect {
return Rect{ width: side, height: side }
}
// file: main.vyi
import { println } from "@fmt"
import { square } from "./rect"
fn main() !u8 {
println(square(3).area()) // prints 9
return Ok(0)
}A parameter written r: Rect carries the Rect its annotation names where the
parameter is written, whatever its argument carried. The full list of places a
written type comes from is under
methods on a type binding.
Scope first, the pocket last
A method in scope at the call is found before anything in the pocket, and a same-signature method in scope overrides the pocket's. Importing a type brings none of its methods into scope; they reach its values through the pocket.
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
export fn (r: Rect) name() [*con]u8 { return "rectangle" }
// file: main.vyi
import { println } from "@fmt"
import { Rect } from "./rect"
fn (r: Rect) name() [*con]u8 { return "box" }
fn main() !u8 {
con r = Rect{ width: 2, height: 3 }
println(r.name()) // prints box
return Ok(0)
}A method in scope applies to every value of its type at that call, whichever version of the type the value carries. The pocket a value arrived with matters only for methods the calling scope does not have.
An override replaces along the path
When a file exports a method with the same name and signature as one in the pocket it imported, and re-exports the type, its method takes the original's place for every file that imports the type from it:
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
export fn (r: Rect) name() [*con]u8 { return "rectangle" }
// file: ui.vyi
import { Rect } from "./rect"
export fn (r: Rect) name() [*con]u8 { return "panel" }
export { Rect }
// file: main.vyi
import { println } from "@fmt"
import { Rect } from "./ui"
fn main() !u8 {
con r = Rect{ width: 2, height: 3 }
println(r.name()) // prints panel
return Ok(0)
}Each re-export works like a subclass of the pocket it imported: it holds what that file added over everything it inherited, and a redefinition overrides the inherited method. The analogy stops at method bodies.
A method body is resolved where it is defined
The method a call reaches runs its body in the scope where the method is written, and its receiver carries the binding its own written type names there. A method defined further along the path is invisible to it: there is no late binding.
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
export fn (r: Rect) name() [*con]u8 { return "rectangle" }
export fn (r: Rect) title() [*con]u8 { return r.name() }
// file: ui.vyi
import { Rect } from "./rect"
export fn (r: Rect) name() [*con]u8 { return "panel" }
export { Rect }
// file: main.vyi
import { println } from "@fmt"
import { Rect } from "./ui"
fn main() !u8 {
con r = Rect{ width: 2, height: 3 }
println(r.name()) // prints panel
println(r.title()) // prints rectangle
return Ok(0)
}title is written in rect.vyi, so its call to name finds the name
declared there.
When a method's result is written as its receiver's own type, the call gives back the version of the type it was called on, so a chain of such calls keeps the caller's version. A result of any other type carries the binding its written type names where the method is defined.
Parameters, generics, and interfaces
A value handed to code in another file reaches a method there in one of three
ways, and each decides differently which method runs. Here b.vyi receives a
Foo three ways and calls m on it:
// file: a.vyi
export struct Foo { pub v: i32 }
export interface HasM {
fn (h: ~HasM) m() i32,
}
export fn (f: Foo) m() i32 { return 1 }
// file: b.vyi
import { Foo, HasM } from "./a"
export fn byType(s: Foo) i32 { return s.m() }
export fn byGeneric(x: _) i32 { return x.m() }
export fn byInterface(h: HasM) i32 { return h.m() }
// file: main.vyi
import { println } from "@fmt"
import { Foo } from "./a"
import { byType, byGeneric, byInterface } from "./b"
fn (f: Foo) m() i32 { return 3 }
fn main() !u8 {
con v = Foo{ v: 0 }
println(byType(v)) // prints 1
println(byGeneric(v)) // prints 3
println(byInterface(&v)) // prints 3
return Ok(0)
}main.vyi's own m is | byType(v) | byGeneric(v) | byInterface(&v) |
|---|---|---|---|
declared at file level (beside its binding of Foo) | a.vyi's | main.vyi's | main.vyi's |
| declared inside the function that makes the call | a.vyi's | a.vyi's | main.vyi's |
imported by the method item Foo.m | a.vyi's | a.vyi's | the imported one |
- A parameter with a written type carries the binding that type names where it is written.
s.m()inb.vyiresolves withb.vyi's scope and its binding's pocket, whatever the caller had. - A generic parameter takes the argument's type together with the pocket the argument carries. The body sees the methods in scope where the generic is written, plus that pocket. A method in the caller's scope that is not in the pocket (declared in a function body, or imported by item) is not seen.
- An interface takes its methods where the value is converted to it: each method is looked up as a call written at the conversion would be, scope first, then the value's pocket. A call through the interface runs the methods found there, so a conversion written in
main.vyiuses anymin scope there. Only the methods the interface declares are callable through it.
Importing methods
A method item Type.name in an import list brings the methods called name
that the imported file exports with that receiver, every overload it matches,
into the importing file's scope. It binds no value and brings nothing else from
the file. The importing file need not import the type. This is how you reach a
method on a type no import can name, such as a primitive or an array pointer.
// file: ints.vyi
export fn (n: i32) squared() i32 { return n * n }
// file: main.vyi
import { println } from "@fmt"
import { i32.squared } from "./ints"
fn main() !u8 {
con side: i32 = 7
println(side.squared()) // prints 49
return Ok(0)
}| Item | Brings |
|---|---|
Point.sum | methods named sum whose receiver is a Point value |
*mut Point.move | methods whose receiver is *mut Point |
*Point.move | *mut Point and *con Point receivers |
~Point.move | Point, *mut Point, and *con Point receivers |
Box(i32).sum | the method declared on Box(i32) |
Box(_).sum | every Box receiver, generic ones included |
_.sum | every receiver |
i32.squared, [*con]u8.first | a receiver type with no name, written as the method declares it |
Point.@add | an operator method, by its @ name |
Point.sum: total | the methods, callable in this file as total |
- The receiver is written as the method declares it, or as a type pattern over it. A pointer receiver is written with its pointer:
Point.movenames only aPointvalue receiver. - The type in an item is resolved in the exporting file's terms and matched by the declaration it names there:
Disc.areanamesfn (c: Circle) area()when the exporting file importedCircleasDisc. - A rename to an
@name makes the method that file's operator. - A file passes on a method it imported with the same form,
export { Point.sum }. A rename in anexportitem is a parse error. - A bare import name is only a function, type, or value. A name the file exports only as a method is an error, with a note giving the method item to write. A method item that names no exported method is an error with a note saying what the file does export under that name.
// file: ints.vyi
export fn (n: i32) squared() i32 { return n * n }
// file: main.vyi
import { squared } from "./ints" // error: "./ints" has no exported member "squared"
fn main() !u8 {
con side: i32 = 7
return Ok(u8(side.squared()))
}Methods on a type binding
type Id = u32 makes a binding Id whose value is the type u32. It is not a
new type: an Id is a u32 as data, typeof it is u32, and the two convert
both ways with no cast. But it is a binding of its own, and it carries its own
methods. A method whose receiver names the binding belongs to the binding: a
value whose written type is Id has it, on top of every method u32 has, and
a plain u32 does not.
import { println } from "@fmt"
type Id = u32
fn (id: Id) next() Id { return id + 1 }
fn main() !u8 {
con first: Id = 41
println(first.next()) // prints 42
return Ok(0)
}type Id = u32
fn (id: Id) next() Id { return id + 1 }
fn main() !u8 {
con count: u32 = 7
con after = count.next() // error: type u32 has no method "next"
return Ok(0)
}The note says that next is a method of Id and count is a u32.
A value's written type comes from:
- a binding's or parameter's annotation (
con a: Id,n: Id, through a pointerp: *mut Id); an unannotated binding takes its initializer's; - a struct field, an enum payload slot, a tuple element, an array or array-pointer element (
[4]Id,[*con]Id) and a loop variable over one, and a pointer's target (*p,&a); - the result type of what a call calls: a function, the chosen overload, a method (
Id.zero(),a.next()), a function value with a written result type (fn() Id), or an operator method; - a cast:
Id(x)carriesId, andu32(a)carries nothing; - a generic instance written with the binding as an argument: a binder that unwraps
?IdcarriesId, and so doesb.valueforb: Box(Id).
A parameter carries what its own annotation names: n: u32 given an Id is a
plain u32 inside the callee. The result of an operator on a primitive
(a + 1) carries nothing.
Every receiver form reaches a binding: fn (x: Id), fn (p: *mut Id),
fn (p: *con Id), and fn (Id) zero(), called as Id.zero(). A binding of
any type carries methods: of a struct (type Panel = Rect), an enum, a generic
instance (type IntBox = Box(i32)), or an array pointer
(type Bytes = [*con]u8). A binding of a binding has both: with type A = u32
and type B = A, a B has the methods of B, A, and u32.
When a binding declares a method with the same name and signature as one on the type it names, a value carrying the binding calls the binding's, and a value of the plain type calls the type's. Scope still comes first: a same-signature method on the named type declared in a nearer scope wins over the binding's declared further out.
Methods declared in a block
A method declared inside a function body or block is visible throughout that block, above its declaration too, and unknown outside it. It may use known values, types, and other names in scope, but never a run-time value of the enclosing function. Pass the value as a parameter, or write a closure:
struct Order { quantity: i32 }
fn show(bonus: i32) i32 {
fn (o: Order) boosted() i32 { return o.quantity + bonus } // error: a method declared in a block cannot use "bonus"
return Order{ quantity: 1 }.boosted()
}Resolution and duplicates
Two different types can carry same-named methods with no conflict; the receiver's type picks the method.
Two methods with the same name, the same receiver (the same type through the same binding, in the same receiver form), and the same parameter and result types, declared in one scope, are a duplicate declaration, as two such functions are:
struct Order { quantity: i32 }
fn (o: Order) total() i32 { return 1 }
fn (o: Order) total() i32 { return 2 } // error: duplicate declaration of method "total" on OrderTwo bindings of one type (type A = i32, type B = i32) are two receivers.
Same-signature methods in different scopes resolve by the order in
method sets are scope-determined: the
nearest scope wins. At one scope level, a method on a
type binding the value carries is nearer than one
on the type the binding names. Declaring your own version of a library's method
changes your calls, never the library's.
The builtin scope and :<markBuiltIn()
Every file's outermost scope includes the builtin scope, where the prelude
lives (Optional, Result, Array, and Range). A method declared with
:<markBuiltIn() in a package that is part of the
program goes there, and every file can call it without an import. This is how
a package adds a method to a type no import can name: @core's @hash makes
every primitive hashable, so HashMap works on any key type, and @fmt's
intoString gives print a way to render each primitive.
The declaring package's manifest must opt in with hasBuiltIns: true. As the
outermost scope, the builtin scope loses to every nearer scope: anything
declared or imported in a file shadows it.
Overload selection
Functions and methods may share a name when their parameter types differ; the arguments select. A free function's candidates are the functions of that name in the scope the name resolves to: the file's own and those its imports bring. Between two of the same signature, the nearer wins: the file's own over an import, a later import over an earlier one (calls). A method's candidates are found through the receiver as above.
| Differs by | Free function | Method |
|---|---|---|
| number of arguments | selects | selects |
| receiver type | selects | |
| parameter types | selects | selects |
import { println } from "@fmt"
struct Cart { items: i32 }
fn (c: Cart) describe() [*con]u8 { return "a cart" }
fn (c: Cart) describe(verbose: bool) [*con]u8 { return "a full cart" }
fn label(n: i32) [*con]u8 { return "number" }
fn label(b: bool) [*con]u8 { return "flag" }
fn main() !u8 {
con cart = Cart{ items: 2 }
println(cart.describe()) // prints a cart
println(cart.describe(true)) // prints a full cart
println(label(5)) // prints number
println(label(false)) // prints flag
return Ok(0)
}An untyped number literal takes the parameter type of the one overload it can select. Arguments that fit no overload are an error naming the candidates. The argument count counts suppliable arguments: a call may leave out trailing parameters that have defaults (guide 04).
Named as a value instead of called, an overloaded function or static method is
the overload whose signature is the function type the position expects (an
annotated binding, a parameter, a field, a return type). With no function type
there, or no overload of that type, it is an error naming the candidates. A
function or static method with a known parameter is not a value.
Interfaces
An interface is a set of method signatures. A type satisfies it where methods
with matching names and signatures can be found for the type: there is no
implements, and the type's author never opts in. A value becomes an interface
value through a pointer, &d.
Each interface method declares its receiver with the interface's name, exactly
or as a type pattern: s: Sink (the value),
s: *mut Sink or s: *con Sink (exactly that pointer), s: *Sink (either
pointer), s: ~Sink (any of them). A method implements it only when its own
receiver is one the pattern admits.
import { println } from "@fmt"
interface Speaker {
fn (s: ~Speaker) speak() [*con]u8,
}
struct Dog { name: [*con]u8 }
fn (d: Dog) speak() [*con]u8 { return "woof" }
fn main() !u8 {
con rex = Dog{ name: "Rex" }
con speaker: Speaker = &rex
println(speaker.speak()) // prints woof
return Ok(0)
}The methods are found where the value is converted, by the same lookup as a call written there: scope first, then the value's pocket. The interface value keeps the methods found there and uses them wherever it goes (guide 12). So your method on another package's type satisfies your interface where you convert, two files can convert the same type with their own methods without affecting each other, and a method declared somewhere else in the program, in no scope at the conversion and not in the value's pocket, does not count:
// file: telemetry.vyi
export struct Buffer { pub payload: i32 }
// file: reading.vyi
import { Buffer } from "./telemetry"
export fn (b: Buffer) read() i32 { return b.payload }
// file: main.vyi
import { Buffer } from "./telemetry"
interface Reader {
fn (r: ~Reader) read() i32,
}
fn main() !u8 {
con b = Buffer{ payload: 9 }
con r: Reader = &b // error: this value has type *con Buffer, but the binding is declared Reader
return Ok(0)
}- Methods on the interface itself. An interface is a type, so it can be a receiver. A method declared on an interface is callable on any satisfying value and calls back through the declared methods;
@mem'sAllocatorprovidesnewanddeleteon top ofallocandfreethis way. Called on a concrete value, the value is converted to the interface at the call. - Generic receivers. A method with a generic receiver (
fn (b: Box(T)) get()) is found for theTof the value being converted (guide 12).
Union receivers
A method call on a union value (e: SaveError | NetError) calls the method of
whichever member the value holds at run time. Every member must have the
method; a member without it rejects the call with
`method "describe" is not defined for union member NetError`.
The members' methods may return different types. The call's type is then the union of their result types (identical results give that one type).
import { println } from "@fmt"
enum SaveError { DiskFull }
enum NetError { Timeout }
fn (e: SaveError) describe() [*con]u8 { return "disk full" }
fn (e: NetError) describe() [*con]u8 { return "timed out" }
fn report(e: SaveError | NetError) {
println(e.describe())
}
fn main() !u8 {
report(Timeout) // prints timed out
return Ok(0)
}known parameters work as on any receiver: each member's method is
instantiated from the call's known arguments.
The receiver is the member value: a union holds its member inline, with no
separate place for a pointer receiver to point at, so pointer-receiver methods
take no part in union calls. To change a member, select it with match typeof
and build a new union value.
@-methods and member access
The @ is part of an operator method's name. Plain member access never finds
one: a.add(b) does not find @add.
struct Money { cents: i32 }
fn (a: Money) @add(b: Money) Money {
return Money{ cents: a.cents + b.cents }
}
fn main() !u8 {
con price = Money{ cents: 100 }
con total = price.add(price) // error: type Money has no method "add"
return Ok(0)
}An operator method is reached through its operator (a + b) or its @
spelling (a.@add(b)), and both resolve by the rules on this page. The table
of operators and their methods is in operators.
See also: operators, guide 14, Modules and packages for imports and exports, and guide 12, Interfaces.