A container owns its elements
An Array<T> of owners owns its elements too. append moves the element in, and releasing the array releases everything it holds. You never free an element separately.
Between building an element and handing it over, the element is still yours. errdefer covers that gap. It releases the value if the step in between fails, and does nothing on the successful path where ownership moves on. The compiler asks for that guard when a failure would otherwise strand the value.
fn collect(texts: [string]) -> Result<Array<Buffer>, Error> {
let mut words = Array.new<Buffer>()
errdefer words.deinit()
for text in texts {
let mut word = Buffer.new()
errdefer word.deinit()
word.append(text)?
words.append(word)?
}
ok(words)
}
fn main() {
let mut words = collect(["moon", "shine"]).unwrap()
defer words.deinit()
println(words.len())
println(words.get(0).view())
}
Examples use the moon toolchain version shown beside each result.
Output & diagnostics
Expected: 2 moon
Ctrl/⌘+Enter runs the current lesson.