DeployU
Interviews / Backend Engineering / What is the `defer` keyword and what is it used for in Go?

What is the `defer` keyword and what is it used for in Go?

conceptual Core Concepts Interactive Quiz Code Examples

The Scenario

You are a backend engineer at a fintech company. You are writing a new service that needs to interact with a database. You need to make sure that the database connection is always closed, even if an error occurs.

The Challenge

Explain what the defer keyword is in Go and how you would use it to solve this problem. What are the key benefits of using defer?

Wrong Approach

A junior engineer might try to solve this problem by using a `try...finally` block, which does not exist in Go. They might not be aware of the `defer` keyword, which is the standard way to handle this problem in Go.

Right Approach

A senior engineer would know that `defer` is the perfect tool for this job. They would be able to explain what `defer` is and how to use it to make sure that the database connection is always closed, even if an error occurs.

Step 1: Understand What defer Is

The defer keyword is used to schedule a function call to be executed just before the function that contains the defer statement returns.

Step 2: Use defer to Close the Database Connection

Here’s how we can use defer to make sure that the database connection is always closed:

package main

import (
    "database/sql"
    "fmt"
)

func main() {
    db, err := sql.Open("mysql", "user:password@/dbname")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // ... (your database code) ...
}

In this example, the db.Close() function will be called just before the main function returns, even if an error occurs.

The Benefits of Using defer

BenefitDescription
Readabilitydefer makes it easy to see what cleanup operations need to be performed.
Reliabilitydefer guarantees that the cleanup operations will be performed, even if an error occurs.

Multiple defer Statements

If you have multiple defer statements in a function, they will be executed in last-in, first-out (LIFO) order.

package main

import "fmt"

func main() {
    defer fmt.Println("first")
    defer fmt.Println("second")
    defer fmt.Println("third")
}

This will print:

third
second
first

Practice Question

You are writing a function that opens a file, writes to it, and then closes it. Which of the following would be the most appropriate way to close the file?