Guides · 12
Interfaces
An interface names a set of methods. Any value whose type has those methods
can become a value of the interface type, and code written against the
interface works with all of them: one function can take a square, a rectangle,
or any other shape, as long as it has an area method.
In Vyi, a type doesn't own its methods. The methods you can call on a value are the ones in scope where you call them (guide 04). An interface value follows the same rule at one particular place: where the value is converted to the interface. It keeps the methods found there, and uses them wherever it goes. This guide builds up to that idea, then covers methods declared on an interface, generic interfaces, and the interfaces in the standard library.
Declaring an interface
An interface lists method signatures, separated by commas like struct fields. Each method declares its receiver, typed with the interface's own name:
import { println } from "@fmt"
interface Shape {
fn (s: ~Shape) area() i32,
}
struct Square { side: i32 }
fn (sq: Square) area() i32 {
return sq.side * sq.side
}
fn main() !u8 {
con tile = Square{ side: 3 }
con shape: Shape = &tile
println(shape.area()) // prints 9
return Ok(0)
}con shape: Shape = &tile converts a pointer to tile into a Shape. The ~
in ~Shape lets the implementing method take the value or a pointer to it;
a later section lists the
choices. shape.area() calls Square's area.
Square never says it is a Shape. Vyi has no implements: a type satisfies
an interface when it has each method the interface lists. So a type can
satisfy an interface its author never heard of.
interface Shape { ... } is short for a type binding. This declares the same
interface:
type Shape = interface {
fn (s: ~Shape) area() i32,
}A type without the methods can't be converted:
interface Shape {
fn (s: ~Shape) area() i32,
}
struct Line { length: i32 }
fn main() !u8 {
con edge = Line{ length: 4 }
con shape: Shape = &edge // error: this value has type *con Line, but the binding is declared Shape
return Ok(0)
}An interface value points at its value
An interface value doesn't hold a copy of the value. It holds a pointer to it,
together with the methods it will call. That's why you convert &tile and not
tile, and why every Shape has the same size whatever it points at.
Converting the value itself is an error:
interface Shape {
fn (s: ~Shape) area() i32,
}
struct Square { side: i32 }
fn (sq: Square) area() i32 {
return sq.side * sq.side
}
fn main() !u8 {
con tile = Square{ side: 3 }
con shape: Shape = tile // error: this value has type Square, but the binding is declared Shape
return Ok(0)
}Because it points, an interface value can't outlive what it points at, and follows the same rules as any pointer (guide 09). A function can't return an interface value made from one of its own bindings:
interface Shape {
fn (s: ~Shape) area() i32,
}
struct Square { side: i32 }
fn (sq: Square) area() i32 {
return sq.side * sq.side
}
fn unitSquare() Shape {
con unit = Square{ side: 1 }
return &unit // error: escapes via return
}One function, many types
A parameter of interface type accepts a value of any type that satisfies the interface. Each call runs the methods of the type it was given:
import { println } from "@fmt"
interface Shape {
fn (s: ~Shape) area() i32,
}
struct Square { side: i32 }
struct Rect { width: i32, height: i32 }
fn (sq: Square) area() i32 { return sq.side * sq.side }
fn (r: Rect) area() i32 { return r.width * r.height }
fn report(s: Shape) {
println(s.area())
}
fn main() !u8 {
con tile = Square{ side: 3 }
con door = Rect{ width: 2, height: 5 }
report(&tile) // prints 9
report(&door) // prints 10
return Ok(0)
}There is one report function. Each Shape it receives brings its own area.
An interface type goes anywhere a type goes: a struct field, a function's
result, or a mut binding that holds a different type later:
import { println } from "@fmt"
interface Shape {
fn (s: ~Shape) area() i32,
}
struct Square { side: i32 }
struct Rect { width: i32, height: i32 }
fn (sq: Square) area() i32 { return sq.side * sq.side }
fn (r: Rect) area() i32 { return r.width * r.height }
fn main() !u8 {
con tile = Square{ side: 3 }
con door = Rect{ width: 2, height: 5 }
mut current: Shape = &tile
println(current.area()) // prints 9
current = &door
println(current.area()) // prints 10
return Ok(0)
}Only the interface's own methods can be called on an interface value. If
Square had a perimeter method, current.perimeter() would be an error,
because Shape doesn't list it.
Any type can satisfy an interface
Methods can be declared on any type, including i32, bool, and [*con]u8
(guide 04),
so any type can satisfy an interface. @fmt declares an IntoString
interface, with the one method println uses, intoString, and declares that
method on the integer types, bool, char, and byte strings. So a pointer to
an i32 or a bool converts to an IntoString:
import { IntoString, print, println } from "@fmt"
fn show(label: [*con]u8, value: IntoString) {
print(label)
println(value)
}
fn main() !u8 {
con count = 3
con ready = true
show("count: ", &count) // prints count: 3
show("ready: ", &ready) // prints ready: true
return Ok(0)
}println itself doesn't take an interface. Its parameter is typed _
(guide 11), so the compiler makes a copy of
println for each argument type, and each copy calls that type's intoString
directly. That is the choice you have whenever a function works on many types:
- A
_orknowntype parameter gives one copy of the function per type. It takes the value itself, and calls go straight to the method. - An interface parameter gives one function for every type. It takes an interface value made from a pointer, and each call goes through the methods that interface value carries.
Reach for an interface when values of different types have to share one type: in one variable, one struct field, or one parameter of a function that isn't copied per type.
The receiver an interface method declares
The receiver of an interface method says what an implementing method may take:
| Receiver in the interface | The implementing method may take |
|---|---|
s: Shape | the value |
s: *mut Shape | a *mut pointer, so it may change the value |
s: *con Shape | a *con pointer |
s: *Shape | a pointer of either kind |
s: ~Shape | the value, or a pointer of either kind |
A method that changes its value takes a *mut receiver, and an interface
that needs one says so:
import { println } from "@fmt"
interface Counter {
fn (c: *mut Counter) increment(),
fn (c: ~Counter) total() i32,
}
struct Clicks { count: i32 }
fn (k: *mut Clicks) increment() { k.count += 1 }
fn (k: Clicks) total() i32 { return k.count }
fn main() !u8 {
mut clicks = Clicks{ count: 0 }
con counter: Counter = &clicks
counter.increment()
counter.increment()
println(counter.total()) // prints 2
return Ok(0)
}A method whose receiver the interface doesn't allow doesn't satisfy it.
Thermometer promises that read only reads. Sensor's read also counts
how often it was read, so it takes a *mut receiver, and Sensor isn't a
Thermometer:
interface Thermometer {
fn (t: *con Thermometer) read() i32,
}
struct Sensor { celsius: i32, reads: i32 }
fn (s: *mut Sensor) read() i32 {
s.reads += 1
return s.celsius
}
fn main() !u8 {
mut probe = Sensor{ celsius: 21, reads: 0 }
con t: Thermometer = &probe // error: does not implement
return Ok(0)
}The full message names both receivers: Thermometer.read declares
*con Thermometer, and the read on Sensor takes *mut Sensor.
The receiver is required. An interface method with no receiver, or with a receiver that isn't the interface, is an error in the interface itself.
The methods come from where you convert
When a value is converted to an interface, the compiler looks up each of the interface's methods for the value's type, exactly as it would for a direct call written at that spot: first in the scope there, then among the methods that travel with the type. The interface value keeps what it found. Wherever the value goes afterwards, calls through it run those methods.
So two places in a program can give the same type different behavior. Here
each function declares its own greeting for User inside its body, where
only that function can see it:
import { println } from "@fmt"
interface Greeter {
fn (g: ~Greeter) greeting() [*con]u8,
}
struct User { name: [*con]u8 }
fn formal(u: *con User) Greeter {
fn (u: User) greeting() [*con]u8 { return "Good morning" }
return u
}
fn casual(u: *con User) Greeter {
fn (u: User) greeting() [*con]u8 { return "Hi" }
return u
}
fn main() !u8 {
con ada = User{ name: "Ada" }
println(formal(&ada).greeting()) // prints Good morning
println(casual(&ada).greeting()) // prints Hi
return Ok(0)
}main has no greeting method in scope, so ada.greeting() would be an
error there. The calls work because each Greeter carries the greeting that
was in scope where return u converted it.
Methods that travel with the type
The second place the lookup searches is the type's pocket: the methods that travel with the type through imports. A method exported from the file that declares a type is in its pocket, and every file that imports the type gets it. A file that imports the type, exports more methods beside it, and re-exports it adds those to the pocket for its own importers. Guide 14 covers pockets in full.
A conversion uses the pocket's method unless a method with the same signature is in scope, and then the one in scope wins:
// file: order.vyi
export struct Order { pub total: i32 }
export fn (o: Order) label() [*con]u8 {
return "Order"
}
// file: main.vyi
import { println } from "@fmt"
import { Order } from "./order"
interface Labeled {
fn (l: ~Labeled) label() [*con]u8,
}
fn plain(o: *con Order) Labeled {
return o
}
fn gift(o: *con Order) Labeled {
fn (o: Order) label() [*con]u8 { return "Gift" }
return o
}
fn main() !u8 {
con order = Order{ total: 30 }
println(plain(&order).label()) // prints Order
println(gift(&order).label()) // prints Gift
return Ok(0)
}In plain, no label is in scope, so the conversion takes the one Order
brought from order.vyi. In gift, the label declared in the body is in
scope, and it wins.
This is also how you make a type you don't control satisfy your interface: declare the missing method on it in your own file, and convert where that method is in scope. A method that is neither in scope at the conversion nor in the type's pocket doesn't count, even if another file of the program declares it. The conversion is an error, as a direct call would be.
Methods on an interface
An interface is a type, so a method can be declared on it. Such a method works for every type that satisfies the interface. You call it on the value itself, and the conversion happens for you:
import { println } from "@fmt"
interface Shape {
fn (s: ~Shape) area() i32,
}
fn (s: Shape) fitsOn(tableArea: i32) bool {
return s.area() <= tableArea
}
struct Square { side: i32 }
fn (sq: Square) area() i32 {
return sq.side * sq.side
}
fn main() !u8 {
con tile = Square{ side: 3 }
println(tile.fitsOn(10)) // prints true
println(tile.fitsOn(4)) // prints false
return Ok(0)
}Square declares only area, and gets fitsOn from Shape. An interface
can keep the list of required methods short and offer more on top of them.
Generic interfaces
A generic interface is a function that returns an interface type, the same way a generic struct is a function that returns a struct type (guide 11):
import { println } from "@fmt"
fn Source(known T: type) type {
return interface {
fn (s: *mut Source(T)) next() T,
}
}
struct Countdown { left: i32 }
fn (c: *mut Countdown) next() i32 {
c.left -= 1
return c.left
}
fn main() !u8 {
mut launch = Countdown{ left: 3 }
con src: Source(i32) = &launch
println(src.next()) // prints 2
println(src.next()) // prints 1
return Ok(0)
}Source(i32) is an interface whose next returns an i32. Like every generic
type, each Source(i32) in the program is the same type.
Values of generic types convert like any other. A method declared on
Grid(T) is a method of every Grid, so a Grid(u8) satisfies Shape:
import { println } from "@fmt"
interface Shape {
fn (s: ~Shape) area() i32,
}
fn Grid(known T: type) type {
return struct { rows: T, cols: T }
}
fn (g: Grid(T)) area() i32 {
return i32(g.rows * g.cols)
}
fn main() !u8 {
con board: Grid(u8) = _{ rows: 3, cols: 4 }
con s: Shape = &board
println(s.area()) // prints 12
return Ok(0)
}Interfaces in the standard library
Three interfaces run through the standard library:
Allocatorfrom@mem: anything that hands out memory (guide 09). It requiresallocandfree, and declaresnewanddeleteon the interface itself.Writerfrom@io: anything that accepts bytes, throughwrite(buf: [*con]u8) error!i32. Standard output is one, and so is aBufferin memory.IntoStringfrom@fmt: anything that can write itself onto aWriter(guide 10).
A function that takes one of them works with every implementation, and the
caller picks which. This greet writes to standard output, and then into a
Buffer:
import { Writer, stdout } from "@io"
import { Buffer, systemAllocator } from "@mem"
import { print } from "@fmt"
fn greet(out: Writer) error!i32 {
return out.write("Hello\n")
}
fn main() !u8 {
try greet(&stdout) // prints Hello
mut saved = Buffer.fromAlloc(systemAllocator)
defer saved.deinit()
try greet(&saved)
print(saved.asBytes()) // prints Hello
return Ok(0)
}Take the interface in your own functions the same way, and let callers choose what goes behind it.
See also: the methods and dispatch reference.