Back to Blog

Anonymous Functions & Closures (Factory Pattern) - Go Tutorial for Beginners #13

Sandy LaneSandy Lane

Video: Anonymous Functions & Closures (Factory Pattern) - Go Tutorial for Beginners #13 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Anonymous Functions & Closures (Factory Pattern) in Go

Anonymous functions and closures are powerful features in Go that enable flexible and stateful programming. This tutorial covers how to define anonymous functions, use closures to capture variables from outer scopes, and implement the factory pattern to create specialized functions dynamically.

Code

package main

import "fmt"

func main() {
  // Anonymous function assigned to a variable
  greet := func(name string) {
    fmt.Println("Hello,", name)
  }
  greet("Alice") // Output: Hello, Alice

  // Immediately Invoked Function Expression (IIFE)
  func() {
    fmt.Println("I run immediately!")
  }()

  // Closure capturing an outer variable
  count := 0
  increment := func() int {
    count++           // modifies outer variable 'count'
    return count
  }
  fmt.Println(increment()) // Output: 1
  fmt.Println(increment()) // Output: 2

  // Factory pattern: returns a function specialized by 'factor'
  multiplier := func(factor int) func(int) int {
    return func(n int) int {
      return n * factor
    }
  }
  double := multiplier(2)
  triple := multiplier(3)

  fmt.Println(double(5)) // Output: 10
  fmt.Println(triple(5)) // Output: 15
}

Key Points

  • Anonymous functions can be defined inline and assigned to variables for flexible use.
  • IIFEs run immediately upon definition, useful for isolated logic or initialization.
  • Closures capture and modify variables from their surrounding scope, enabling stateful functions.
  • The factory pattern uses closures to create specialized functions with customized behavior.
  • These patterns are widely applicable for creating loggers, counters, multipliers, and more in Go.