Closures Functions in Golang
Closures are a special case of anonymous functions. Closures are anonymous functions which access the variables defined outside the body of the function.
Example
Anonymous function accessing the variable defined outside body.
package main
import "fmt"
func main() {
l := 20
b := 30
func() {
var area int
area = l * b
fmt.Println(area)
}()
}
Example
Anonymous function accessing variable on each iteration of loop inside function body.
package main
import "fmt"
func main() {
for i := 10.0; i < 100; i += 10.0 {
rad := func() float64 {
return i * 39.370
}()
fmt.Printf("%.2f Meter = %.2f Inch\n", i, rad)
}
}
Most Helpful This Week
What is Function in Golang
Naming Conventions for Golang Functions
User Defined Function Types in Golang
Simple function with parameters in Golang
Anonymous Functions in Golang
Golang Functions Returning Multiple Values
Creating a Function in Golang
Simple function with return value in Golang
Higher Order Functions in Golang
The return values of a function can be named in Golang
Golang Passing Address to a Function