Skip to main content
Module 3 · Lesson 4 of 514/50 in the course~12 min
Module lessons (4/5)

Closures and functions as values

Lesson preview5 hands-on exercises readyCourse Go · Module 3 — Functions

Anonymous functions that capture variables from the external context; adapter and factory patterns.

What you'll learn in this lesson

  • Write anonymous functions (func literals) by assigning them to variables or executing them immediately.
  • Capture private state from external lexical scope via closure.
  • Avoid loop-catching bugs by knowing the semantics of for introduced in Go 1.22.

Overview

Since functions are first-class values, in Go you can define them inline without a name and return them from other functions: if they reference variables of the surrounding scope, they become closures that keep those variables alive even after the creating function has done return.

Each call to a factory allocates an independent environment for the captured variables:

Sections covered in this lesson

  1. 1Anonymous functions and immediate invocation
  2. 2Closure: Capture the external scope for reference
  3. 3Typed callbacks and function aliases
  4. 4Functional options and middleware with closure
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 3 — Functions

Unlock "Closures and functions as values" and the full Course Go curriculum

Anonymous functions that capture variables from the external context; adapter and factory patterns.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Go plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.