Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
func main() {
n := 0
next := func() int { n++; return n }
fmt.Println(next(), next(), next())
}1 2 3
- Expecting
1 1 1: the function literal does not copyn; it uses the variable itself, so each call sees the value the previous call left. - Expecting
0 1 2:n++is a statement that runs beforereturn n, so the first call already returns1.
- What would a second
next2 := func() int { n++; return n }see after these three calls? - How would you give each counter its own
n?