Give a block its own memory
The manual form of the same thing is to say which allocator a block uses. context.allocator.use(.Arena) selects a fresh arena for the rest of the enclosing block. Everything allocated while it is selected, including inside the functions the block calls, is released together when the block ends.
A loop body is the usual place for one. Each iteration gets its own arena, so the strings and arrays it builds are reclaimed at the closing brace instead of piling up for the life of the program.
fn main() {
let mut total = 0
for line in ["a,b", "c,d", "e,f"] {
context.allocator.use(.Arena)
let parts = line.split(",")
total += parts.len()
}
println(total)
}
Examples use the moon toolchain version shown beside each result.
Output & diagnostics
Expected: 6
Ctrl/⌘+Enter runs the current lesson.