Anonymous functions
What are anonymous functions? A description is a function that has not been given a name, for example:
package main
import (
"fmt"
)
func main(a) {
// Anonymous function definition method 1
func (s string){
fmt.Printf("Anonymous function :%s\n",s)
}("Definition Method 1")
// Anonymous function definition method 2
fn:=func (s string){
fmt.Printf("Anonymous function :%s\n",s)
}
fn("Definition Mode 2")}Copy the code
closure
A closure is actually an instance of a function, that is, a structure that exists in memory. In terms of implementation, an anonymous function that does not capture free variables can be implemented as a function pointer, or directly inline to the call point. If it does capture free variables, it will be a closure.
Closures are meant to contain both the function pointer and the environment. In compilation optimization, closures that do not capture free variables can be optimized into ordinary functions without assigning closure structures, a compilation technique known as function jump.
Closure = function + reference environment
package main
import (
"fmt"
)
func main(a) {
// c copies the closure copy
c:=Closure()
c() // Call the closure
c() // Call the closure
// C2 copies the new closure
c2:=Closure()
c2() // Call the closure
}
/ * closure * /
func Closure(a) func(a){
i:=1
return func(a) {
i++
fmt.Printf("The closure, I = % d \ n",i)
}
}
Copy the code
Output:
Closure, I =2 closure, I =3 closure, I =2Copy the code
Escape analysis
The GO language recognizes the scope of variables through Escape Analyze and automatically allocates variables on the heap. Allocating closure environment variables on the heap is the foundation of Go’s implementation of closures.
The above code can be analyzed with the following command:
go build --gcflags=-m main.go
Copy the code
Output:
# command-line-arguments
./main.go:23:13: inlining call to fmt.Printf
./main.go:20:2: moved to heap: i
./main.go:21:9: func literal escapes to heap
./main.go:23:14: i escapes to heap
./main.go:23:13: []interface{} {... } does not escape <autogenerated>:1: .this does not escape
Copy the code
**./main.go:23:14: I escapes to heap**