Interface value
In the Interface lesson, wheel.Area() could only ever mean Circle's Area: the compiler knew wheel was a Circle. An interface is also a type in its own right. A view of type &Shape can borrow a circle now and a rectangle a moment later, and a call through it runs whichever Area belongs to the value behind it. That is what lets values of different types share one function, one parameter list or one loop.
Making a view
// The annotation is what turns a circle into a Shape. The view borrows `wheel` and copies
// nothing.
let shape: &Shape = wheel;
PrintLine("holding a {} with area {}", shape.Name(), shape.Area());
shape is a reference to the circle, together with a note of which type is behind it. Without the annotation, let shape = wheel; would simply be another Circle.
Dynamic dispatch
Now hand a rectangle to a function that takes a &Shape:
func Describe(shape: &Shape) {
PrintLine("holding a {} with area {}", shape.Name(), shape.Area());
}
// One function, another type: the same calls now run Rectangle's code.
Describe(door);
The call shape.Area() is written once, yet it runs different code for each value. It follows the note to the Area of whatever type is behind the view:
flowchart LR
invoke["`shape.Area()`"] --> note{"Which type is<br/>behind `shape`?"}
note -- "a `Circle`" --> c["`Circle`'s `Area`<br/>`3.14 × radius × radius`"]
note -- "a `Rectangle`" --> r["`Rectangle`'s `Area`<br/>`width × height`"]
c --> result["a `float64`"]
r --> resultChoosing the function while the program runs, by the value behind the view rather than by anything written at the call, is called dynamic dispatch. Compare it with a call on a concrete type:
| Call | Type of the receiver | Which Area runs is decided |
|---|---|---|
wheel.Area() | Circle | when the program is compiled — always Circle's |
shape.Area() | &Shape | while it runs — by the value behind the view |
Many types in one call
An array needs one element type, so a circle and a rectangle cannot share one directly. A variadic parameter of views can take both:
// A variadic parameter of views takes any mix of shapes, each borrowed for the call.
func TotalArea(shapes: &Shape...) -> float64 {
var total = 0.0;
for each in shapes {
total += each.Area();
}
return total;
}
TotalArea(wheel, door) borrows each argument as a &Shape, and the loop calls Area on every one without knowing, or caring, which shape it is: 12.56 + 2.0 = 14.56.
A view, not a copy
// A view reaches the value itself, so it sees the value as it is when it is used.
var balloon = Circle { radius: 1.0 };
balloon.radius = 2.0;
let seen: &Shape = balloon;
PrintLine("the balloon's area is {}, and the view sees {}", balloon.Area(), seen.Area());
The view copies nothing: it reaches the balloon itself, so it reports the grown area, 12.56. Because it is a borrow, it lasts only as long as the code using it, like any reference. To keep a Shape in a field or an array, a program stores a handle instead, the interface type without the &: the address of a value stored elsewhere. Making one from a value with state takes a pointer and an unsafe promise that the value outlives the handle, which the Pointer lesson introduces.
Only the promise is visible
Through a &Shape, you can reach only what Shape promises. Even while a rectangle is behind it, shape.width is rejected with error: interface type 'Shape' has no member 'width', and a method of Rectangle's own, such as IsSquare from the previous lesson, is refused the same way. The view might reach a circle the next time that line runs, and a circle has neither.
The program
The whole lesson is one package in the Examples repository. Its comments explain every step.
// A variable can have an interface as its type. `let shape: &Shape = wheel;` borrows the circle
// as a Shape: a view of it, together with a note of which type it is.
//
// A call such as `shape.Area()` follows the note to Circle's own `Area`. Borrow a rectangle the
// same way and the very same call runs Rectangle's `Area` instead. Which function runs is decided
// while the program runs, by the value behind the view, not by anything written at the call.
// That is called dynamic dispatch, and it is what lets values of different types share one
// function, one parameter list, or one loop.
//
// A view is a borrow, so it lasts as long as the code using it and copies nothing. To keep a
// Shape in a field or an array, a program stores a handle instead, `Shape` without the `&`, which
// the Pointer lesson in Part 15 shows how to make.
import Io::PrintLine;
interface Shape {
func Area() -> float64;
func Name() -> char8[..];
}
struct Circle {
radius: float64;
}
struct Rectangle {
width: float64;
height: float64;
}
extend Circle : Shape {
func Area(&self) -> float64 {
return 3.14 * self.radius * self.radius;
}
func Name(&self) -> char8[..] {
return "circle";
}
}
extend Rectangle : Shape {
func Area(&self) -> float64 {
return self.width * self.height;
}
func Name(&self) -> char8[..] {
return "rectangle";
}
}
func Describe(shape: &Shape) {
PrintLine("holding a {} with area {}", shape.Name(), shape.Area());
}
// A variadic parameter of views takes any mix of shapes, each borrowed for the call.
func TotalArea(shapes: &Shape...) -> float64 {
var total = 0.0;
for each in shapes {
total += each.Area();
}
return total;
}
func Main() -> int {
let wheel = Circle { radius: 2.0 };
let door = Rectangle { width: 1.0, height: 2.0 };
// The annotation is what turns a circle into a Shape. The view borrows `wheel` and copies
// nothing.
let shape: &Shape = wheel;
PrintLine("holding a {} with area {}", shape.Name(), shape.Area());
// One function, another type: the same calls now run Rectangle's code.
Describe(door);
// A circle and a rectangle cannot share an array: `let shapes = [wheel, door];` is refused
// with "array element 2 has type 'Rectangle', but element 1 established element type
// 'Circle'". As Shapes they can share one call, each argument borrowed as a view.
PrintLine("total area {}", TotalArea(wheel, door));
// A view reaches the value itself, so it sees the value as it is when it is used.
var balloon = Circle { radius: 1.0 };
balloon.radius = 2.0;
let seen: &Shape = balloon;
PrintLine("the balloon's area is {}, and the view sees {}", balloon.Area(), seen.Area());
// Only what Shape promises can be reached through it. `shape.width` is rejected even when a
// rectangle is behind it: "interface type 'Shape' has no member 'width'".
return 0;
}
Run it
cd Examples/Interfaces/InterfaceValue
rux run
holding a circle with area 12.56
holding a rectangle with area 2.0
total area 14.56
the balloon's area is 12.56, and the view sees 12.56
Common mistakes
Try it yourself
- Add a
Trianglethat keeps theShapepromise, and pass it toTotalAreaas a third argument. - Write a
Largest(shapes: &Shape...) -> char8[..]that returns the name of the shape with the largest area. - Change
balloon.radiusafter makingseen, then readseen.Area(). What does the compiler say, and why?
Learn more
- Interface values in the Rux Reference — views, handles and bounds
- Reference — the borrow a view is
- Interface parameter — reading and changing a value through an interface
- Sum type — the other way to hold "one of several types", when the list of types is fixed