12 · Object-Oriented Programming
Fixed arrays and const generic sizes
Check a packet's exact length and infer that length in reusable functions.
On this page
A packet has a fixed number of samples. Keep that count in its type and infer it when calling a reusable function. The example also stores a callable and updates one sample without changing the packet's length.
Check a packet's exact length and infer that length in reusable functions.
17-fixed-arrays.zolo
// Sum a packet whose size is checked at the boundary.
struct Buffer<const N: int> {
bytes: [int; N]
}
fn sum<const N: int>(samples: [int; N]) -> int {
let total = 0
for sample in samples {
total += sample
}
total
}
fn describe<const N: int>(samples: [int; N], label: str = "packet") -> str =
"{label}: {N} samples, sum {sum(samples)}"
let packet: Buffer<3> = Buffer { bytes: [12, 18, 30] }
let tools = .{ describe: describe }
print(tools.describe(packet.bytes))
packet.bytes[0] = 15
print(describe(packet.bytes, "updated"))
A length must be known at compilation. Const generic functions receive the inferred size as an immutable integer; fixed arrays reject operations that resize them. See the reference for static arithmetic, defaults, imports and unsupported adapters.
See also