Help Understanding Basic Concepts (Closures and Method Receivers)

Written by
Link to Post

https://www.reddit.com/r/golang/comments/ae4sxd/help_understanding_basic_concepts_closures_and/

I am going through gobyexample and could use some clarification on the closure/anonymous function example:

func intSeq() func() int { i := 0 return func() int { i++ return i } } func main() { nextInt := intSeq() fmt.Println(nextInt()) fmt.Println(nextInt()) fmt.Println(nextInt()) } 

prints

$ go run closures.go 1 2 3 

So I know that intSeq() is executed the first time when it is set to nextInt, but I am confused how each successive call increments the counter when it seems like it gets set to 0 each time. Is the outer function only executed the one time and then only the inner function gets executed over and over?

Also methods that have recievers:

func (r *rect) area() int { return r.width * r.height } 

Why declare them like that rather than passing the struct in as a parameter?

submitted by /u/AtooZ
[link] [comments]

Article Tags:
· ·
Article Categories:
reddit

Leave a Reply