Go · Level 2 Functions

Closures

Return a function that remembers its own state in Go: a closure that counts requests per user, with every counter keeping separate counts.

  • a closure keeps the variables around it
  • each call to the factory gets fresh state
  • state inside the returned function resets

A closure is a function that keeps the variables around it, so NewID can return a function with its own memory. Trap: a variable declared inside the returned function starts fresh on every call.

func NewID(prefix string) func() string {
    n := 0
    return func() string {
        n++
        return fmt.Sprint(prefix, n)
    }
}

Write NewHitCounter() func(user string) int: each call records a hit for user and returns that user's total so far; every counter has its own counts. Example: hits for "ana", "ana", "bo" return 1, 2, 1.

solution.go
Test Suites Pending
Output