LEARN VOID / DATA & BEHAVIOR
Composition
Build a type from smaller pieces of behavior.
value struct movement:
x: i32
func (m movement) move(amount: i32):
m.x += amount
struct combat:
health: i32
func (c combat) hit(amount: i32):
c.health -= amount
struct player:
using motion: movement
using combat
value struct kit:
using movement
using combat
func entry(value: i32) -> i32:
var shared = combat(health = 100)
var p = player(motion = movement(x = value), combat = shared)
p.move(2)
p.motion.move(3)
p.hit(4)
var a = kit(movement = movement(x = 1), combat = shared)
var b = a
b.move(2)
b.hit(4)
return p.x + a.x + b.x + a.healthInput 5Expected result 106
Compose through using
using promotes selected members from a contained component. A component can be named explicitly, as in using motion: movement, or use its type name, as in using combat.
Keep the component’s semantics
The movement value copies with its containing value struct. The managed combat object retains shared identity. Composing the two does not turn a reference into a value or silently duplicate its state.
Follow the aliases
The player’s motion moves from 5 to 10. The two kit values have independent motion positions, 1 and 3, while both damage operations affect shared health, leaving 92. The result is 10 + 1 + 3 + 92 = 106.