Function#

Methods are Functions#

In Go, methods can be treated as functions. When a method is referenced without an instance, it is called a method expression. The receiver becomes the first argument of the function.

eg.

type Adder struct {
    start int
}

func (a Adder) AddTo(val int) int {
    return a.start + val
}

func main() {
    // Method Expression
    f := Adder.AddTo               // signature: func(Adder, int) int
    fmt.Println(f(Adder{10}, 15))  // 25
}

Declaration Scope#

There is a key difference in where methods and functions can be declared:

  • Methods: Can only be defined at the package block level.
  • Functions: Can be defined inside any block (eg. inside another function).

defer Evaluation Timing & Anonymous Closures (defer fn() vs defer func() { ... }())#

While Go defers the actual execution (call) of a function until the surrounding function returns, the function value itself (function pointer) and all passed arguments are eagerly evaluated immediately when the defer statement is executed.

Therefore, if a variable holding the function pointer or an argument may be reassigned later in the function, it must be wrapped inside an anonymous closure (defer func() { ... }()).

Dimensiondefer fn(arg) (Direct Registration)defer func() { fn(arg) }() (Closure Registration)
Evaluation TimingEvaluates and copies the value immediately when defer is reachedEvaluates the variable’s latest reference when the surrounding function returns
When Safe to UseWhen fn and arg are never reassigned after the defer statementWhen fn or arg may be reassigned inside loops, branches, or reconnect/restart logic
Typical Examplesch := make(chan int)
defer close(ch) (channel pointer never changes)
Supervisor pattern where cancelFunc is replaced on restart,
or modifying named return error values

(1) When Function/Argument Variables Are Reassigned (Supervisor / Reconnect Pattern)#

If a resource handle (context.CancelFunc, file, or network connection) is replaced inside a loop, registering defer cancel() directly captures only the initial function pointer, leaving the final active resource leaked upon exit.

func supervisor(ctx context.Context) {
    var cancelWorker context.CancelFunc

    startWorker := func() {
        var workerCtx context.Context
        // Each restart overwrites cancelWorker with a brand-new CancelFunc!
        workerCtx, cancelWorker = context.WithCancel(ctx)
        go runWorker(workerCtx)
    }

    startWorker() // Worker #1 started (cancelWorker = CancelFunc_1)

    // [WRONG]: defer cancelWorker()
    // Captures CancelFunc_1 immediately. Even if Worker #2 is spawned later,
    // exit will invoke CancelFunc_1 again while leaking Worker #2!

    // [CORRECT]: Capture variable reference via closure
    defer func() {
        // Evaluated at function exit: looks up whatever cancelWorker holds right now
        // (CancelFunc_2, CancelFunc_3, etc.) and cancels the active worker.
        if cancelWorker != nil {
            cancelWorker()
        }
    }()

    // Worker #1 dies and restarts -> cancelWorker is reassigned to CancelFunc_2!
    cancelWorker()
    startWorker()
}

(2) Why defer close(ch) Is Safe Without a Closure#

func worker() <-chan int {
    ch := make(chan int)
    go func() {
        // The variable ch is initialized once via make() and is never reassigned (ch = ...).
        // Eagerly evaluating the channel pointer at the defer line always points to the exact same channel.
        defer close(ch)
        ch <- 42
    }()
    return ch
}

# go