CodeNebula
Go🔧Core Languagebeginner

Defer

Go · Core Language · Run with go run

Explanation

`defer` schedules a function call to run when the surrounding function returns — regardless of whether it returns normally or via `panic`. Multiple defers execute in LIFO order. The primary use is resource cleanup: closing files, releasing locks, closing database connections.

Real-World Scenario

Opening a file and deferring its close immediately after the open check ensures the file is always closed, even if the function returns early due to an error ten lines later.

Quick Snippet

snippet.go
func copyFile(src, dst string) error {
    in, err := os.Open(src)
    if err != nil {
        return err
    }
    defer in.Close() // guaranteed to run when copyFile returns

    out, err := os.Create(dst)
    if err != nil {
        return err
    }
    defer out.Close()

    _, err = io.Copy(out, in)
    return err
}

Full Example

defer.go
// Compile: go run defer.go
// Output:
//   opening resource
//   working...
//   closing resource  ← runs even on early return
package main

import "fmt"

type Resource struct{ name string }

func (r *Resource) Close() { fmt.Println("closing resource") }

func open(name string) *Resource {
	fmt.Println("opening resource")
	return &Resource{name: name}
}

func doWork() error {
	r := open("db-connection")
	defer r.Close() // guaranteed to run when doWork returns

	fmt.Println("working...")
	return nil
}

func main() {
	_ = doWork()
}
Run command
go run defer.go