What is the “defer” keyword in Go?

In the Go programming language, defer is a keyword that allows developers to delay the execution of a function until the current functions returns. What throws some people off is that the deferred function’s arguments are evaluated immediately, but the function itself doesn’t fire until the wrapping function exits.

Simple defer example – hello world

func main() {
    defer fmt.Println("world") // deferred until main() exits
    fmt.Println("hello")
 }

// prints:
// hello
// world

When would you want to defer something?

After programming in Go, it’s really hard to remember how I dealt with closing connections or files in other languages. The defer statement is a very clean way to deal with any sort of “cleanup” that needs to happen in a function.

resp, err := http.Get(url)
if err != nil{
    log.Println(err)
}
defer resp.Body.Close()

In Go’s standard http library, the documentation points out that HTTP responses must be closed by the client when it’s finished. The client must close the response body when finished with it.

#golang #mailing-list

How to Properly Use Defer in Golang
1.35 GEEK