Errdefer
errdefer can be used to release resources in case of
error.
It works like defer, but the statement only runs if the program leaves the scope to return an error value:
const std = @import("std");
const print = std.debug.print;
fn f(error_please: bool) !void {
errdefer print("errdefer in f\n", .{});
if (error_please) {
print("f: returning with error\n", .{});
return error.MyError;
}
print("f: returning successfully\n", .{});
}
pub fn main() void {
f(false) catch {};
print("\n", .{});
f(true) catch {};
}$ zig run errdefer.zig
f: returning successfully
f: returning with error
errdefer in f
Next example: Arrays.