This is the 14th day of my participation in Gwen Challenge

These reviews

Previous articles focused on function declarations and parameter passing in the Go language. This article will continue to introduce the concepts and use of anonymous functions and closures.

Anonymous functions do not have a function name, only a function body, which is initialized only when called. Anonymous functions are typically assigned as a type to variables of type function and are often used to implement functions such as callbacks and closures.

Anonymous functions and closures

Golang’s anonymous functions are declared as follows:

func(params)(return params){
	function body
}
Copy the code

Anonymous functions are declared in much the same way as normal functions are defined, except that they have no name. We can call an anonymous function directly after it has been declared, as in the following example:

func (name string){
	fmt.Println("My name is ", name)
}("Wang Xiaoer")
Copy the code

An anonymous function can be called immediately after it has been declared, followed by a list of arguments for the call. In addition, we can assign anonymous functions to variables of function type for multiple calls or evaluations, as shown in the following example:

currentTime := func(a) {
	fmt.Println(time.Now())
}
// Call an anonymous function
currentTime()
Copy the code

In the example above, we implemented a simple timer using an anonymous function and assigned it to currentTime. Each time currentTime is called, we know the latest time on the current system.

A common scenario for anonymous functions is to use them as callback functions. In the following example, we define a function that takes an input of a string and an anonymous function, and then uses the anonymous function to process the string as follows:

package main

import "fmt"

func proc(input string, processor func(str string))  {
	// Call an anonymous function
	processor(input)
}

func main(a)  {
	proc("Wang Xiaoer".func(str string) {
		for _, v := range str{
			fmt.Printf("%c\n", v)
		}
	})
}
Copy the code

The anonymous function in the above code is used as a callback function to process the passed string. Users can pass different anonymous functions to achieve different processing operations on the string according to their own needs.

Closures are functions that carry state; they are Bridges that connect the inside of a function to the outside of a function. With closures, we can read variables inside a function. We can also use closures to encapsulate private states and keep them resident in memory.

A closure can reference and modify variables above its scope. Variables captured in a closure will persist throughout the life of the closure. The function itself does not store information, but variables in a closure enable the closure itself to store information. We can use closure features to implement a simple counter as follows:


package main

import "fmt"

func createCounter(initial int) func(a) int {

	if initial < 0{
		initial = 0
	}

	// Reference initial to create a closure
	return func(a) int{
		initial++
		// Returns the current count
		returninitial; }}func main(a)  {

	// count 1
	c1 := createCounter(1)

	fmt.Println(c1()) / / 2
	fmt.Println(c1()) / / 3

	// count 2
	c2 := createCounter(10)

	fmt.Println(c2()) / / 11
	fmt.Println(c1()) / / 4

}
Copy the code

The createCounter function returns a closure that encapsulates the counted initial and is not directly accessible from external code. Variables in different closures do not interfere with each other, and both c1 and C2 counters count independently.

summary

This article focuses on anonymous functions and closures. In Go, functions can be passed or used like normal variables, similar to C’s callback functions. The difference is that the Go language allows anonymous functions to be defined in code at any time. The anonymous function of Go is a closure. Closures can be function objects or anonymous functions, which in the case of the type system means representing code as well as data.