Dienstag, 17. November 2009

defer in go

"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." GocourseDay1.pdf

leet look folowing programm:

package main

import "fmt"

func b() {
fmt.Printf("called b()\n");
}

func a() int {
fmt.Printf("start a()\n");
defer b();
fmt.Printf("ended a()\n");
return 0;
}

func main() {
fmt.Printf("start main\n");
fmt.Printf("call a()\n");
a();
fmt.Printf("after a()\n");
fmt.Printf("\n");
}


a() call with defer b(). But the outprint show:

./6.out
start main
call a()
start a()
ended a()
called b()
after a()



we can see that b() will be called before a() return.

=> defer is useful for closing fds, unlocking mutexes, etc.

defer is simmilar to atexit() for main() in C.

futher example:

package main

import "fmt"

func trace(s string) string {

fmt.Print("entering:", s, "\n");
return s
}
func un(s string) {
fmt.Print("leaving:", s, "\n")
}
func a() {

defer un(trace("a"));
fmt.Print("in a\n")
}
func b() {

defer un(trace("b"));
fmt.Print("in b\n");
a()
}
func main() { b() }


the output is:

./6.out
entering:b
in b
entering:a
in a
leaving:a
leaving:b

as we can see: defer f1(f2()) f2() is called immediately but f1() is called at ending.

Keine Kommentare:

Kommentar veröffentlichen