Anonymous Functions and Closures Golang Tutorial 03 — Code Thursday
Subscribed to: https://medium.com/@kerstan
Hi guys, I am Kerstan. Today is Code Thursday.
I will share you about Anonymous Functions and Closures in Golang.
So, let’s get started.
1. Anonymous Function
Go language supports anonymous functions, implying that functions can be passed around or utilized like ordinary variables. Anonymous functions can be assigned to variables, serving as fields within structures.
Anonymous functions have the capability to directly access external variables.
package main
import "fmt"
func main() {
// 1
var v func(a int) int
// Anonymous function, that is, there is no function name
v = func(a int) int {
return a * a
}
fmt.Println(v(6))
// 2
fn := func() {
fmt.Println("Hello World")
}
// The calling of anonymous function
fn()
}
2. Closures
The Go language supports anonymous functions, enabling the creation of closures. An anonymous function acts as an “inline” statement or expression. One of the strengths of anonymous functions is their ability to directly use the variables inside the function, without the need for…