Structs
Group related values into a named type with fields and defaults.
Declaration
Write the type name, a colon, and struct. Inside the body, each field has a name and a type, with an optional default value.
Point : struct {
x : f32 = 0
y : f32 = 0
}
| Part | Meaning |
|---|---|
Point | The new structure's name. |
: struct | Declares a structure type. |
x : f32 | A named field with an explicit type. |
= 0 | The field's default initializer. |
Initialization and fields
Use Type { ... } to construct a value. Named field initializers begin with a dot. Use var if the value needs to change.
origin := Point {}
var point := Point { .x = 10, .y = 20 }
point.x = 30
horizontal := point.x Extension methods
Define an ordinary function with @extension. Its first parameter is the receiver. A pointer receiver lets the function update the original structure.
@extension
translate : func(self : ^Point, dx : f32, dy : f32) {
self.x += dx
self.y += dy
}
point.translate(2, -4) Generic structures
Add type parameters after struct, then supply concrete types when constructing a value.
Pair : struct<T, U> {
first : T
second : U
}
pair := Pair<i32, bool> { .first = 42, .second = true } Embedding
Use inline inside a structure to embed another structure and expose its fields directly.
This example uses the Point type declared above. NamedPoint embeds its x and y fields and adds a name field of its own.
NamedPoint : struct {
inline Point
name : string = ""
}
var point := NamedPoint { .x = 10, .y = 20, .name = "spawn" }
// Access the embedded fields directly.
point.x = 30
horizontal := point.x // 30
vertical := point.y // 20
label := point.name // "spawn"
inline Point lets you initialize the embedded fields with .x and .y, then read or update them with point.x and point.y. The name field belongs to NamedPoint.