Structs
Structs are Vexel's primary mechanism for grouping related data together. They define a named type with a fixed set of typed fields.
Defining a Struct
Structs are declared with the struct keyword at the top level of a file. Each field is declared on its own indented line as name: type.
struct Vec2:
x: float
y: float
struct Entity:
x: float
y: float
speed: float
health: int
name: str Creating Instances
Instances are created with the new keyword followed by the struct name and positional arguments matching the field declaration order.
let pos: Vec2 = new Vec2(3.0, 4.0)
let player: Entity = new Entity(0.0, 0.0, 5.0, 100, "Hero") Accessing Fields
Fields are read and written using dot notation.
let pos: Vec2 = new Vec2(3.0, 4.0)
print(pos.x) # 3.0
print(pos.y) # 4.0
# Mutate a field
let player: Entity = new Entity(0.0, 0.0, 5.0, 100, "Hero")
player.x = 10.0
player.health -= 25 Structs as Function Parameters
Structs are passed by value. When a struct is passed to a function, the function receives a copy. Modifying the copy does not affect the original.
fn length_sq(v: Vec2) -> float:
return v.x * v.x + v.y * v.y
fn move_entity(e: Entity, dx: float, dy: float) -> Entity:
# Return a new Entity with updated position
return new Entity(e.x + dx, e.y + dy, e.speed, e.health, e.name)
fn main():
let dir: Vec2 = new Vec2(3.0, 4.0)
print(length_sq(dir)) # 25.0
let p: Entity = new Entity(0.0, 0.0, 5.0, 100, "Hero")
let moved: Entity = move_entity(p, 10.0, 5.0)
print(moved.x) # 10.0