Structs (v0.2.2)

User-defined aggregate types with named fields.

Latest

Overview

Structs group related fields under one type. Each field has a name and an explicit type.

They are useful for records, configuration values, handles, and small pieces of program state.

When a struct has rules about valid values, use helper functions to create or update it in one place.

Primary source: syntax/structure/structure.md

Syntax Signatures

struct Pair @public {
    left: s32,
    right: s32,
}

var p: Pair = new Pair {
    left: 1,
    right: 2,
};

Behavior and Use

Use field access to read or write named fields. If a field must stay consistent with another field, keep that update in a helper function.

For structs shared with C code, check field order and field sizes against the C definition.

Fields and Construction

A struct value is built by naming each field and assigning a value.

Layout and Interop

Structs used across FFI boundaries need stable field expectations.

Example

struct Config @public {
    threads: u32,
    verbose: bool,
}

fn defaultConfig() Config @public {
    return new Config {
        threads: 4,
        verbose: false,
    };
}
struct Counter @public {
    value: s32,
    limit: s32,
}

fn tick(counter: ptr[Counter]) bool @public {
    if counter == nullptr {
        return false;
    }

    if counter->value >= counter->limit {
        return false;
    }

    counter->value = counter->value + 1;
    return true;
}

Back to language reference