You’re almost there. When you call the defer
it will unconditionally deinit
the ArrayList
when the scope ends; int his case when the function ends. So you are returning a uninitialized ArrayList
. To return the initialized ArrayList
while properly uninitializing it in case of error in the function, use errdefer
:
fn isReturn(allocator: Allocator) !std.ArrayList(i32) {
var list = std.ArrayList(i32).init(allocator);
errdefer list.deinit();
try list.append(1);
try list.append(2);
std.debug.print("List: {any}\n", .{list.items});
return list;
}
The caller of the function is now responsable for calling deinit
on the returned ArrayList
.