v0.4.0

Interface Values

An interface is a type in its own right. A value of an interface type reaches a value of any type that implements the interface, together with a note of which type that is, and a call through it runs that type's method. Choosing the method while the program runs, by the value behind it, is dynamic dispatch.

An interface is used in three ways, and each says where the implementing value lives:

WrittenWhat it isChanges reach the original?
shape: &Shapea read-only view: a borrow of an implementing valueit cannot change anything
shape: &var Shapea writable viewyes
args: &Shape...a variadic parameter of read-only viewsit cannot change anything
let shape: Shape = unsafe { @p as Shape };a handle: the address of a value stored elsewhereyes
shapes: Shape[2]an array of handlesyes
<T: Shape>a bound: no dispatch at all—

Views

A view, &I or &var I, is a reference like any other: it borrows the caller's own value, whatever its type, as long as it implements I. Nothing is copied, and the borrow ends with its last use. The conversion from the concrete type happens where the value is passed or bound; no &, cast or call is written.

interface Gauge {
    func Read() -> int32;
    func Adjust(&var self, amount: int32);
}

struct Dial {
    level: int32;
}

extend Dial : Gauge {
    func Read(&self) -> int32 {
        return self.level;
    }

    func Adjust(&var self, amount: int32) {
        self.level += amount;
    }
}

func Show(gauge: &Gauge) {
    PrintLine("reads {}", gauge.Read());
}

func TurnUp(gauge: &var Gauge, amount: int32) {
    gauge.Adjust(amount);
}

func Main() -> int {
    var dial = Dial { level: 4 };
    Show(dial);
    TurnUp(dial, 5);
    PrintLine("dial.level is {}", dial.level);    // 9
    return 0;
}
flowchart LR
    invoke["`gauge.Read()`"] --> note{"Which type is<br/>behind `gauge`?"}
    note -- "a `Dial`" --> c["`Dial`'s `Read`"]
    note -- "a `Meter`" --> s["`Meter`'s `Read`"]

A read-only view may also borrow a temporary, which lives until the end of the block it is written in, so Show(Dial { level: 2 }) works, and so does PrintLine("{}", total + 1): PrintLine takes its arguments as args: &Display.... A writable view needs a place, because writes to a temporary would be lost.

A requirement declared with &var self writes, so it is callable only through a writable view:

error: cannot call 'Adjust' through immutable reference '&Gauge'
  note: 'Adjust' declares a writable receiver '&var Self'
  help: declare the reference as '&var Gauge'

A writable view needs writable storage: passing a let binding to a &var Gauge parameter fails with argument 1 to 'TurnUp' cannot borrow immutable 'fixed' as '&var Gauge'. A writable concrete borrow, &var Dial, converts to a read-only &Gauge as well.

Handles

A view lasts as long as the code using it, so it cannot be kept in a field, an array, or a value returned from a function. What can is an interface value, the interface type written without &: a handle, the address of an implementation and its method table. A handle copies nothing and owns nothing. Copying one copies the address, every copy reaches the same value, and when a handle goes away nothing is destroyed. That is what makes it storable anywhere.

Because a handle copies nothing, no implicit conversion makes one from a value with state, which would have to be copied somewhere first:

error: cannot make interface value 'Shape' from 'Circle'
  note: an interface value is a handle to an implementation stored elsewhere and copies nothing, so only a stateless value converts to one
  help: borrow it as '&Shape', bound a generic parameter by 'Shape', or make a handle from a pointer to it inside 'unsafe'

The same holds for an argument, a field, a return, an assignment, an optional or an array element, for a view (the handle would outlive the borrow) and for a value of a type parameter. A handle comes from one of three places:

  • A stateless value. A struct with no fields and no destructor has nothing to point at, so it converts anywhere and the handle stays valid for the whole program. SystemAllocator is one: Vector<int>(SystemAllocator()) keeps an Allocator handle made this way.
  • A pointer, inside unsafe. @value as Shape makes a handle to what the pointer addresses. The handle is used later without unsafe, so making it is the unsafe step, and its // Safety: comment states the promise: the value outlives every copy of the handle and does not move while one exists. A read-only pointer makes a handle only to an interface none of whose requirements writes its receiver, so @fixed as Gauge with fixed a let is cannot make interface value 'Gauge' from read-only pointer '*Dial'. A function that hands out a handle, such as an arena's Handle, is an unsafe func that passes the same promise to its caller.
  • Another handle, copied, stored, or returned as it is.
var dial = Dial { level: 4 };
// Safety: `dial` is a local that outlives `gauge` and never moves.
let gauge = unsafe { @dial as Gauge };
gauge.Adjust(1);    // writes `dial`: a handle reaches the value itself

A requirement that writes its receiver is callable through any handle, let or var, since the call writes the value the handle addresses, never the handle itself.

Many types in one array

An array has one element type, so values of different types share one only as handles:

// Safety: `wheel` and `block` are locals that outlive `shapes` and never move.
let shapes: Shape[2] = unsafe { [@wheel as Shape, @block as Shape] };
var total = 0.0;
for each in shapes {
    total += each.Area();
}

Without the annotation, the first element decides the element type, and the second is refused: array element 2 has type 'Square', but element 1 established element type 'Circle'.

Only the interface is visible

Through a view or a handle, only the interface's requirements can be reached. The value behind it might be of any implementing type the next time the line runs, so fields and the type's other methods are out of reach:

error: interface type 'Gauge' has no member 'level'

Dynamic dispatch and bounds

A view or handle and a bound both use an interface, in different ways:

View or handle: shape: &ShapeBound: <T: Shape>
Which typeany implementing type, decided while runningone concrete type per instantiation
A method calllooked up through the method tabledirect, and may be inlined
Codeone copy of the functionone copy per concrete type
What comes backthe interface; the concrete type is hiddenthe same T that went in
Mixed types at onceyes — one array, one parameter listno — every T is the same type
Conformancedeclared with extend T : Shapeany type with the required methods

See also