Skip to main content

Structs

A struct is plain data: a set of named, typed fields and nothing else. Where a class bundles data with behaviour, a struct is the shape data takes when it leaves your program, whether to another program or to storage.

Every field carries a number, and every field is a let:

struct Reading {
1. let sensor : string
2. let celsius : f32
3. let count : i32
}

The number, not the name or the order, is what identifies a field once the data has left. That's why it's written by hand, and why a field never changes its number once data has been written with it.

Making one​

A struct is made by naming its fields:

struct Point {
1. let x : i32
2. let y : i32
}

let origin = Point(x = 0, y = 0)
let across = origin.x

A struct has no constructor of its own, so new doesn't make one.

A struct can't change once it's made, so it's a value rather than an instance with an identity of its own.

Data structs​

Marking a struct data says that two with the same field values are the same data:

data struct Point {
1. let x : i32
2. let y : i32
}

Comparing two structs with == is not in V0 yet: compare their fields.

Structs and classes​

Use a class for something your program works with, and a struct for data that crosses a boundary. A struct holds fields and nothing else: no functions, and no var. It's the form data takes between isolates (see Isolates).