$ ./guess_the_languageProblem Solving — fix the bug
Problem Solving — fix the bug · hard · #258

Which fix removes the bug?

func process(items []string) {
	n := 0
	defer fmt.Println("processed", n)
	for range items {
		n++
	}
} // always prints "processed 0"
  1. Declare n with var n int
  2. Defer a closure: defer func() {...}()
  3. Increment with n += 1 instead
  4. Pass a pointer: defer fmt.Println(&n)
A deferred call evaluates its arguments when the defer statement runs, so n is captured as 0. A deferred closure reads n when it finally runs.
Play Problem Solving ▸