Go closure variable scope

前端 未结 3 2096
既然无缘
既然无缘 2021-02-15 16:25

I\'m reading \'CreateSpace An Introduction to Programming in Go 2012\'

and on page 86 I found this evil magic

func makeEvenGenerator() func() uint {
             


        
3条回答
  •  太阳男子
    2021-02-15 17:21

    1) Why is i not resetting ?

    Closures in Go capture variables by reference. That means the inner function holds a reference to the i variable in the outer scope, and each call of it accesses this same variable.

    2) is nextEven() returning and uint or is Println so smart that it can work with everything ?

    fmt.Println() (along with fmt.Print(), fmt.Fprint(), etc.) can work most types. It prints its arguments in the "default format". It is the same thing that is printed using fmt.Printf() using the %v verb.

提交回复
热议问题