leviathan-lang.com / docs / learn
Value types: structs and enums
Structs copied on every bind, mutating methods, and enums with a closed set of members.
Structs
When you want data with no identity (a coordinate, a row, a small record), use a struct. A struct
is copied on every bind, pass, return, and store (deeply), has no identity, and is final. A method
that writes this must be marked mutating.
A struct is copied, not shared
struct Point {
int x; int y;
int dot() => x * x + y * y;
mutating void translate(int dx, int dy) { x = x + dx; y = y + dy; }
}
Point a = Point(3, 4);
Point b = a; // a full copy: b is independent
b.translate(1, 1); // mutates b only; a is still (3, 4)
console.writeln("${a.x}, ${a.y}");
console.writeln("${b.x}, ${b.y}");
console.writeln(a.dot());
3, 4
4, 5
25
Enums
An enum is a value type with a closed set of members carried by int. Members live on the static
side, reached with ::.
Enum members, codes, and lookup by code
enum Status : int { OK = 200, NotFound = 404, Teapot = 418 }
Status s = Status::NotFound;
int code = s.code(); // 404
string txt = s.toString(); // "NotFound"
console.writeln(code);
console.writeln(txt);
Status? found = Status::fromCode(200); // Status?: None if no member matches
if (found != None) {
console.writeln(found.toString());
}
Status? missing = Status::fromCode(1);
if (missing == None) {
console.writeln("no member has code 1");
}
404
NotFound
OK
no member has code 1
Because value structs with all-scalar fields have no identity, an Array<Point> can be stored
column-major automatically for big speedups, with zero change to your code. The reference entry on
columnar arrays explains when that applies.
See also
- Columnar storage of struct arrays — How native builds lay out an array of simple structs column by column, when that applies, and how to turn it off.