Category: Defer

Post Pic

Go – Defer

The defer statement executes a function (or method) when the enclosing function returns. The arguments are evaluated at the point of the defer; the function call happens upon return.
func data(name string) string {
f := os.Open(name, os.O_RDONLY, 0);
defer f.Close();
contents := io.ReadAll(f);
return contents;
}
Useful for closing fds, unlocking mutexes, etc.
Tracing with defer
func trace(s string) { Print(”entering:”, s); }
func [...]