September 2017
Intermediate to advanced
466 pages
9h 33m
English
The defer keyword defers the execution of a function until the surrounding function returns, and is widely used in file I/O operations. This is because it saves you from having to remember when to close an open file.
The file with the Go code that illustrates the use of defer is called defer.go and has four main parts.
The first part is the expected preamble as well as the definition of the a1() function:
package main
import (
"fmt"
)
func a1() {
for i := 0; i < 3; i++ {
defer fmt.Print(i, " ")
}
}
In the previous example, the defer keyword is used with a simple fmt.Print() statement.
The second part is the definition of the a2() function:
func a2() {
for i := 0; i < 3; i++ {
defer func() { fmt.Print(i, " ") }()
}
}
Read now
Unlock full access