Type Aliases
Basic aliases
type Byte = u8;
type Callback = fn(i64) -> void;
type Buffer = []u8;Why use aliases
- Shorten long types used repeatedly
- Give domain-specific names to generated types (
type Ids = collections.Vec_i64;) - Create function pointer types for event signatures
Example
type EventHandler = fn(*u8, i64) -> void;
type Job = fn(*Device) -> Result or JobError;
type Slice = []const u8;
type Table = [256]u32;Type aliases are fully transparent — the compiler treats the alias and the original type as identical.
The right-hand side is a concrete type: a primitive, struct, enum, pointer,
slice, array or function pointer. A fallible return type (i64 or ParseErr)
is not a type of its own and cannot be aliased.
A type alias is private to its module unless it is pub. An importer writes
a pub type qualified, or lists it in a selective import:
// shapes.tape
pub struct Point { x: f64; y: f64; }
pub type Path = []Point;
// app.tape
import shapes from "./shapes.tape";
fn length(p: shapes.Path) -> i64 { return p.len; }Methods resolve through an alias: a method of the type it names is called on a value of the alias or through a pointer to one, the alias of another module’s type included:
// counter.tape
pub struct Counter { n: i64; }
pub fn Counter.add(*self, by: i64) { self.n = self.n + by; }
// facade.tape
import counter from "./counter.tape";
pub type Counter = counter.Counter;
// app.tape
import facade from "./facade.tape";
fn twice(c: *facade.Counter) { c.add(1); c.add(1); }A literal through an alias builds the type it names, a tagged union’s variant included, however many aliases lead to it:
// app.tape
import facade from "./facade.tape";
let c = facade.Counter { n: 0; }; // a counter.Counter
tagged Shape { Circle { r: f64; } Square { side: f64; } }
type Form = Shape;
let s = Form.Circle { r: 1.0; }; // a ShapeThe right-hand side of a pub type may only name types an importer can see
(pub ones, built-in ones): pub type Outer = *Inner; with a private Inner
is a compile error. The stdlib’s component constraints are pub aliases
(ui.Drawable, Constraints).
Last modified: