I am reading Closure example in Mark Summerfield's book Programming in Go Section 5.6.3. He defines Closure as a "function which "captures" any constants and variables that are present in the same scope where it is created, if it refers to them."
He says that one use of closure is anonymous functions (or function literals in Go)
He gives this examples:
addPng := func(name string) string { return name + ".png" }
addJpg := func(name string) string { return name + ".jpg" }
fmt.Println(addPng("filename"), addJpg("filename"))
I understand that anonymous function named addPng
is a wrapper for the string concatenation operator +
.
If I understand correctly, he is assigning an anonymous function a name then calling the function with that name. I don't see the point of this example. If I define the same function addPng
and call it inside main()
I get the same result:
package main
import ("fmt")
func addPng (name string) string {
return name + ".png"
}
func main() {
fmt.Println(addPng("filename"))
}
I understand that I cannot define and use a function inside another function. But why is the anonymous function in Summerfield's example called "Closure"? And why use a wrapper function? What am I missing?