Skip to content

Structs

Structs let you create your own named data types with fields.

type Pair := struct { left right : int };

Adjacent fields can share a type, so left right : int is shorthand for giving both fields the int type.

To create a value, use the struct name followed by a field list.

let pair := Pair { left : 10, right : 20 };

Struct fields are accessed with ..

print(pair.left);
print(pair.right);

Structs can be destructured directly into local bindings.

let {left, right} := pair;
print(left + right);

You can also rename fields while destructuring.

let {left: a, right: b} := Pair { left : 4, right : 6 };
print(a + b);

Functions can destructure struct parameters directly.

const sum_pair_struct := fn ({left: a, right: b} : Pair) => a + b;
const sum_pair_struct_basic := fn ({left, right} : Pair) => left + right;

Structs can also be matched against directly.

match Pair { left : 30, right : 50 } {
{left : 50, right} => print(50 - right),
{left, right} => print(left + right),
_ => {}
};

Calibre also supports tuple-style structs.

type Country := struct (Language);

Use a struct when named fields make the data easier to understand than tuple positions.