Reputation: 274
Below is the code of Function Closures in A Tour of Go, I know a little about function closures but I am a beginner for Go.
package main
import "fmt"
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
func main() {
pos, neg := adder(), adder()
for i := 0; i < 10; i++ {
fmt.Println(
pos(i),
neg(-2*i),
)
}
}
Here are questions:
func adder() func(int) int {
what are [parameter list] and [return_types] respectively?pos, neg := adder(), adder()
, does it mean to assign the function adder to pos and neg, why not it should be pos, neg := adder, adder
?Upvotes: 2
Views: 217
Reputation: 676
Q: for func adder() func(int) int {
what are [parameter list] and [return_types] respectively?
A: Here, we have a function called adder()
that takes no arguments that returns a function func(int) int
which takes an integer and returns an integer.
Q: for the same line with Question.1, why there is (int)
, instead of something like (x int)
?
A: This is the adder()
function
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
Take a look at the function that is being returned, here func(x int) int
already has a named parameter (x
), so we don't need to mention it again at func adder() func(int) int
, because if we'd do something like func adder() func(x int) int
, the x
here has no use.
So if the function that is being returned had, say, 2 parameters (one extra is a string
type), then it would look like the following code:
func adder() func(int, string) int {
sum := 0
return func(x int, y string) int {
sum += x
fmt.Println(y)
return sum
}
}
Notice that we added a string
type at func adder() func(int, string) int {
, that's because the function we are returning takes a string
type.
Q: for pos, neg := adder(), adder(), does it mean to assign the function adder to pos and neg, why not it should be pos, neg := adder, adder?
A: See, when we assign pos
to adder()
(pos := adder()
), pos
becomes a new function, because adder()
returned a function func(int) int
, thus we can do pos(i)
.
Same goes for neg
.
Upvotes: 3