
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 [...]
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 untrace(s string) { Print(”leaving:”, s); }
func a() {
trace(”a”);
defer untrace(”a”);
Print(”in a”)
}
func b() {
trace(”b”);
defer untrace(”b”);
Print(”in b”);
a()
}
func main() { b() }
Args evaluate now, defer later
func trace(s string) string {
Print(”entering:”, s);
return s
}
func un(s string) {
Print(”leaving:”, s)
}
func a() {
defer un(trace(”a”));
Print(”in a”)
}
func b() {
defer un(trace(”b”));
Print(”in b”);
a()
}
func main() { b() }
No related posts.






Leave Your Response