mirror of
https://github.com/bootdotdev/fcc-learn-golang-assets.git
synced 2025-12-10 07:11:19 +00:00
731 B
731 B
Closure Review
A closure is a function that references variables from outside its own function body. The function may access and assign to the referenced variables.
Example Closure
func concatter() func(string) string {
doc := ""
return func(word string) string {
doc += word + " "
return doc
}
}
func main() {
harryPotterAggregator := concatter()
harryPotterAggregator("Mr.")
harryPotterAggregator("and")
harryPotterAggregator("Mrs.")
harryPotterAggregator("Dursley")
harryPotterAggregator("of")
harryPotterAggregator("number")
harryPotterAggregator("four,")
harryPotterAggregator("Privet")
fmt.Println(harryPotterAggregator("Drive"))
// Mr. and Mrs. Dursley of number four, Privet Drive
}