Structs (v0.2.1)
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.
Best Practices
- Initialize every field explicitly in helper constructors.
- Avoid structs that group unrelated data.
- Use dedicated functions for mutation when fields must stay in sync.
Fields and Construction
A struct value is built by naming each field and assigning a value.
- Each field has its own explicit type in the struct declaration.
- new StructName { ... } creates a value with the listed field values.
- Use helper constructors when a struct has required defaults or related fields that must agree.
Layout and Interop
Structs used across FFI boundaries need stable field expectations.
- Field order matters when matching an external layout.
- @packed changes padding behavior. Use it only when the external format requires it.
- When a struct is shared with C code, verify field sizes and alignment with compile-time builtins.
Example
struct Config @public {
threads: u32,
verbose: bool,
}
fn defaultConfig() Config @public {
return new Config {
threads: 4,
verbose: false,
};
}