

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
click for more info
Not enough gems
Cost: 6 gems
1: Functions
incomplete
2: Multiple Parameters
incomplete
3: Unit Test Lessons
incomplete
4: Declaration Syntax
incomplete
5: Passing Variables by Value
incomplete
6: Ignoring Return Values
incomplete
7: Named Return Values
incomplete
8: The Benefits of Named Returns
incomplete
9: Explicit Returns
incomplete
10: Early Returns
incomplete
11: Functions As Values
incomplete
12: Anonymous Functions
incomplete
13: Defer
incomplete
14: Block Scope
incomplete
15: Processing Orders
incomplete
16: Closures
incomplete
17: Currying
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
The defer keyword is a fairly unique feature of Go. It allows a function to be executed automatically just before its enclosing function returns. The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
Deferred functions are typically used to clean up resources that are no longer being used. Often to close database connections, file handlers and the like.
For example:
func GetUsername(dstName, srcName string) (username string, err error) {
// Open a connection to a database
conn, _ := db.Open(srcName)
// Close the connection *anywhere* the GetUsername function returns
defer conn.Close()
username, err = db.FetchUser()
if err != nil {
// The defer statement is auto-executed if we return here
return "", err
}
// The defer statement is auto-executed if we return here
return username, nil
}
In the above example, the conn.Close() function is not called here:
defer conn.Close()
It's called:
// here
return "", err
// or here
return username, nil
Depending on whether the FetchUser function errored. (We'll cover errors later).
Defer is a great way to make sure that something happens before a function exits, even if there are multiple return statements, a common occurrence in Go.
The location of a defer statement inside a function matters. The deferred call is registered at the point where defer is executed, and it will run when the function returns. If you have multiple defer statements in a single function, they are executed in last-in, first-out order (the last deferred call runs first).
For example, you'd want to close a file before trying to remove it:
func CreateTempFile() {
f, _ := os.Create("temp-42.txt")
defer os.Remove(f.Name()) // executed second
defer f.Close() // executed first
fmt.Fprintln(f, "How many roads must a man walk down?")
}
Complete the bootup function.
TEXTIO BOOTUP DONE