Files use .rex, the command is rex, and the crate, runtime prefixes, docs, editor files and examples all use the new name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3.0 KiB
6. Structs and enums
Structs
A struct groups related values. Methods go inside the struct and see the fields directly.
struct Player {
name: string
hp: int
x, y: float // names in a row share a type
func hurt(amount: int) { // changes hp, so Rex knows it modifies the player
hp -= amount
}
func alive(): bool {
return hp > 0
}
}
func main() {
var p = Player{name: "Ada", hp: 10} // fields left out start at zero
p.hurt(4)
print(p.hp, p.alive())
print(p)
}
6 true
Player{name: Ada, hp: 6, x: 0.0, y: 0.0}
Ways to build one:
- Named:
Player{name: "Ada", hp: 10}. Any field may be left out; it starts at0,0.0,false,""or an empty list. - Positional:
Vec2{1.0, 2.0}. Every field must be given.
You never write mut. A method that assigns to a field is detected as changing the
struct, and the compiler stops you from calling it on a const or on a temporary.
Inside a method, a bare name means: a local or parameter first, then a field, then another
method of the same struct (hurt(2)), then a global function.
Structs are values
struct Point { x, y: int }
func main() {
var a = Point{1, 2}
var b = a
b.x = 99
print(a, b)
}
Point{x: 1, y: 2} Point{x: 99, y: 2}
var b = a is a real copy. If you want one value with several owners, see
shared.
Methods that return values, and nested data
struct Vec2 {
x, y: float
func length_squared(): float {
return (x * x + y * y)
}
func plus(o: Vec2): Vec2 {
return Vec2{x + o.x, y + o.y}
}
}
struct Ship {
pos: Vec2
trail: []Vec2
}
func main() {
var s = Ship{pos: Vec2{1.0, 1.0}}
s.trail.push(s.pos)
s.pos = s.pos.plus(Vec2{2.0, 0.0})
print(s.pos, s.trail, s.pos.length_squared())
}
Vec2{x: 3.0, y: 1.0} [Vec2{x: 1.0, y: 1.0}] 10.0
== on whole structs is not available yet; compare the fields.
Enums
An enum is "one of these cases", and each case can carry data.
enum Event {
Quit
Key(code: int)
Click(x, y: int)
func describe(): string {
return match self {
Quit => "quit"
Key(c) => "key {c}"
Click(x, y) => "click at {x},{y}"
}
}
}
func main() {
var e = Event.Click(3, 4)
print(e.describe())
print(Event.Key(65), Event.Quit)
}
click at 3,4
Event.Key(65) Event.Quit
- Build a value with the qualified name:
Event.Key(65),Event.Quit. - Take it apart with
match, which must cover every case. - Inside an enum's methods,
selfis the whole value. - The zero value of an enum is its first case.
==works on enums whose cases carry no data.
Privacy
Everything is private to its file unless you write pub. This matters once you split a
program into several files (next chapters). Inside one file you
never need pub.
Next: Errors and nil