0
0
Goprogramming~10 mins

Why defer is used in Go - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to ensure the file is closed after opening it.

Go
file, err := os.Open("example.txt")
if err != nil {
    log.Fatal(err)
}
[1] file.Close()
Drag options to blanks, or click blank then click option'
Afunc
Bgo
Cdefer
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'go' instead of 'defer' causes the file to close immediately or not at the right time.
2fill in blank
medium

Complete the code to print 'Done' after the function finishes.

Go
func process() {
    [1] fmt.Println("Done")
    fmt.Println("Processing...")
}
Drag options to blanks, or click blank then click option'
Afunc
Bgo
Creturn
Ddefer
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'go' runs the print concurrently, not after the function ends.
3fill in blank
hard

Fix the error by completing the code to close the database connection after use.

Go
func queryDB() {
    db, err := sql.Open("driver", "source")
    if err != nil {
        log.Fatal(err)
    }
    [1] db.Close()
    // perform queries
}
Drag options to blanks, or click blank then click option'
Adefer
Bgo
Creturn
Dfunc
Attempts:
3 left
💡 Hint
Common Mistakes
Not using defer causes the connection to remain open longer than needed.
4fill in blank
hard

Fill both blanks to defer closing the file and unlocking the mutex.

Go
func safeWrite() {
    mu.Lock()
    [1] mu.Unlock()
    file, err := os.Create("data.txt")
    if err != nil {
        log.Fatal(err)
    }
    [2] file.Close()
    // write data
}
Drag options to blanks, or click blank then click option'
Adefer
Bgo
Creturn
Dfunc
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'go' instead of 'defer' causes unlocking or closing to happen too early or concurrently.
5fill in blank
hard

Fill all three blanks to defer closing the file, unlocking the mutex, and printing 'Finished'.

Go
func processFile() {
    mu.Lock()
    [1] mu.Unlock()
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    [2] file.Close()
    [3] fmt.Println("Finished")
    // process file
}
Drag options to blanks, or click blank then click option'
Ago
Bdefer
Creturn
Dfunc
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'go' runs the functions concurrently and immediately, not after the function ends.