WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Go · Basic · question 13 of 100

What is the ’defer’ statement used for in Go?

📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

The ‘defer‘ statement in Go is used to ensure that a function call, usually for cleaning up resources such as closing files or network connections, is executed later in the program just before the surrounding function returns. This helps developers manage resources effectively and avoid code duplication or potential errors.

Using ‘defer‘, you can schedule a function call and make sure it is executed regardless of how or where the surrounding function returns (either normally or via panic). The ‘defer‘ statement has the following general syntax:

defer functionName(arguments)

Consider the following example:

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Open("example.txt")
    if err != nil {
        fmt.Println("Error: ", err)
        return
    }
    defer file.Close()

    // Perform some operations on the file...
}

In this example, the ‘defer‘ statement schedules ‘file.Close()‘ to be called just before the ‘main‘ function returns. This ensures that the file is properly closed even if an error occurred or the function returned early.

In sum, the ‘defer‘ statement in Go allows you to manage resources efficiently, avoid code duplication, and handle potential errors effectively by scheduling a function call to be executed just before the surrounding function returns.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Go interview — then scores it.
📞 Practice Go — free 15 min
📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

All 100 Go questions · All topics