Skip to content

Structs

Chloë Strainge edited this page Oct 14, 2026 · 1 revision

Structs

A struct is a nominal record. Fields are private unless declared pub. Each field has a type, and construction checks required fields and their values.

struct Station
{
    pub name: String,
    pub platforms: Integer,
    pub note: String | (),
}
let $station = Station(name: "Riverside", platforms: 3)
echo $station.name $station.platforms $station.note
Riverside 3 ()

Use attached named construction: Station(name: ..., platforms: ...). Fields admitting () may be omitted. Unknown, repeated, or missing required arguments are errors. Construction does not guess values for required fields.

Encapsulated state

A public factory can construct private storage. External callers use its named parameters; a matching raw construction inside the constructor initializes fields.

struct Gauge { reading: Integer }
fn Gauge::new($initial: Integer): Gauge { Gauge(reading: $initial) }
fn Gauge::get_value(): Integer { $self.::reading }
fn Gauge::set_value($value: Integer) { $self.::reading = $value }
let $gauge = Gauge(initial: 5)
$gauge.value = 12
echo $gauge.value
12

Raw .::reading observes the same access rules while bypassing property dispatch. It is not a way for unrelated code to access private fields. Getters and setters can have independent visibility. Getter-only properties are read-only; setter-only properties cannot be read.

Constructors and getters can return errors, and return contracts are validated. A constructor recursively calling itself without reaching raw construction is rejected. Fields and nested collections obey ordinary value-copy semantics. Native resource fields can still hold shared handles; see I/O.

A deferred let $station: Station binding must be initialized before reading. An optional Station | () instead has an immediately readable unit default.


Related: Methods · Named types · JSON

Clone this wiki locally