preface

What is a closure?

A lot of people have been asking me about closures lately, and I want to get to the point of closure quickly in three ways:

  1. What is a closure?
  2. What are closed packages used for?
  3. What are the effects of closures?

The body of the

What is a closure

Closures are entities that combine functions with their associated environment

Read the above sentence for once.

A closure is a local or global variable that references an external function in an anonymous function

Here’s a simple example to illustrate the above statement:

The impact of closures

Reference local variables

If the function returns a closure that references an external variable

  1. The same function is called multiple times. Each call reallocates memory to internal variables and does not affect external variables

  2. Multiple calls to the returned closure object without reallocating memory and affecting external variables

Here’s an example:

package main


import ( "fmt" )

func colsure(a) func(a) { age := 1

return func (a) { age++ fmt.Println("age: ", age) } }

func main(a) { f := colsure() g := colsure()

// Call the same function multiple times f() // age: 2 g() // age: 2

// Multiple calls to the returned closure object g() // age: 3 g() // age" 4 }

Copy the code

Using global variables

Each call has an effect on an external global variable

package main


import ( "fmt" )

var age = 1 func colsure(a) func(a) { return func (a) { age++ fmt.Println("age: ", age) } }

func main(a) { f := colsure() g := colsure()

f() // age: 2 g() // age: 3 } Copy the code

What are closed packages used for

The original purpose of closures was to reduce global variables by implicitly passing shared variables during function calls. The result of this approach is a lack of directness and clarity, so closures are generally not recommended

Closure mind mapping

The last

If this article is helpful, please give me a thumbs up at 👍 and thank you for your support!

If there are any mistakes in this article, thank you for your criticism and advice!