Back to course

Defer: Cleaning Up Resources

Full Course: Zig Programming From Zero to Hero

Defer

defer is used to execute a statement when exiting the current block scope. This is extremely useful for manual memory management.

zig fn deferExample() void { const file = openFile(); defer closeFile(file);

// Use file...
// closeFile(file) will be called automatically when this function ends.

}

If you have multiple defer statements, they are executed in reverse order (LIFO).