Closures and anonymous functions Golang

1. anonymous function

Anonymous function is not the function of the function name, as shown below.

func test() int {
    max := func(a, b int) int {
        if a > b {
            return a
        } else {
            return b
        }
    }(3, 4)
    return max
}

func main() {
    primeCnt := make(chan int, 1)
    N := 10
    go func(N int) {
        cnt := 0
        for i := 2; i < N; i++ {
            var j int
            for j = 2; j <= int(math.Sqrt(float64(i))); j++ {
                if i%j == 0 {
                    break
                }
            }
            if j > int(math.Sqrt(float64(i))) {
                cnt++
                fmt.Println(i)
            }
        }
        primeCnt <- cnt
    }(N)
    fmt.Println("totalNum:", <- primeCnt) 
}

Basically anonymous functions are also nothing to say. . .

2. Closure

Closures feeling that the return value is a function of the anonymous function. . . Look at an example of it (◉3◉)

package main

import (
    "fmt"
)

func squares() func() int {
    var x int
    return func() int {
        x++
        return x * x
    }
}

func main() {
    f := squares()
    fmt.Println(f())
    fmt.Println(f())
    fmt.Println(f())
}

Operating results as shown below, you can see three calls f (), get a different x. Even if x is a local variable squares, but the variable x life cycle is extended to three times a function call (f ()). Why is this? Let's look at another case.

package main

import (
    "fmt"
)

func squares() func() int {
    var x int
    return func() int {
        x++
        return x * x
    }
}

func main() {
    f := squares()
    f1 := squares()
    fmt.Println(f())
    fmt.Println(f())
    fmt.Println(f())

    fmt.Println(f1())
    fmt.Println(f1())
    fmt.Println(f1())
}

 

See the bar. Another variable is started again. Hey hey hey. Why is this so, in a word, memory escape. What is memory escape, simply put, is the original variables on the stack and ran to the pile. Of course we talked about so simple, another day to write an article to talk to you Taijun memory escape, hey hey hey. So how to detect memory program has not happened escape it. Eau go build the tools. As shown below.

From the figure we can see that the variable x is moved to the heap, which also explains why x life cycle can be extended.

 

reference

https://juejin.im/post/5c850d035188257ec629e73e  analysis of the closure,

"Go Programming Language"

https://www.do1618.com/archives/1328/go-%E5%86%85%E5%AD%98%E9%80%83%E9%80%B8%E8%AF%A6%E7%BB % 86% E5% 88% 86 % E6% 9E% 90 /  analysis of escape memory

Guess you like

Origin www.cnblogs.com/dennis-wong/p/11628288.html