LEARN VOID / DATA & BEHAVIOR
Callable structs
Let a small object express an operation.
value struct multiplier:
amount: i32
func (m multiplier) call(value: i32) -> i32:
return m.amount * value
struct counter:
value: i32
func (c counter) call(value: i32) -> i32:
c.value += value
return c.value
func make() -> multiplier:
return multiplier(amount = 3)
func apply<t>(action: t, value: i32) -> i32:
return action(value)
func entry(value: i32) -> i32:
var m = multiplier(amount = 2)
var c = counter()
var alias = c
if apply(m, 3) != 6:
return -100
var first = m(value)
var second = alias(2)
return first + second + make()(1) + c(1)Input 5Expected result 18
Define call on a receiver
A compatible call method lets an instance be invoked with ordinary function-call syntax. The multiplier value stores an amount and multiplies its argument.
Keep value and reference behavior
The managed counter mutates its shared state when called through an alias. The multiplier remains a value. Using call does not create a new ownership or memory model.
Pass an operation to a generic
apply accepts a concrete callable and invokes it. A returned temporary can also be called, as in make()(1). Input 5 returns 18. Callable structs obey the normal visibility, receiver-effect and readonly rules.