Part of Golang for Beginners

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

Take the quiz on the full lesson page
Test what you've read · interactive walkthrough

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.
Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.