The closure base GO

A, closures appreciated

Closures are a combination of environmental and anonymous functions referenced anonymous function. Anonymous function has characteristics dynamically created, this feature allows anonymous function without passing parameters by way of, you can directly reference external variables.

This function is similar to a conventional direct use of global variables, personal understanding is: it refers to anonymous functions and variables and the environment, similar to the conventional function references the global environment variables in a package.

 

 

 

package main

import "fmt"

func main() {
    // first embodiment 
    RES: = Adder ()
    fmt.Printf("%T \n", res)
    for i := 0; i < 5; i++ {
        fmt.Println("i=", i, "sum=", res(i))
    }

    res2 := adder2()
    fmt.Println("res2=", res2)
    fmt.Println("result=", res2())
    fmt.Printf("%T \n", res2)
    
    // second way anonymous closure 
    RES3: FUNC = () FUNC () int {
        num = 0 
        return func () int {
            whether ++
             return whether
        }
    }()
    fmt.Println("res3=", res2)
    fmt.Println("result=", res3())
}



// definition of a function implemented closure accumulator 
FUNC Adder () FUNC ( int ) int {
    I am = 0 
    state = func (whether int ) int {
        sum + = whether the
         return to
    }
    return res
}
// definition of a function realized without reference closure accumulator 
FUNC adder2 () FUNC () int {
    I am = 0 
    state = func () int {
        sum++
        return sum
    }
    fmt.Println("res=", res)
    return res
}

 No closure when the function is one-shot deal, after the function completes can not change the value of the variable in the function (memory should be released); after you have a closure function becomes the value of a variable, not as long as the variable is released, the function has been in a state of survival and exclusive, so you can change the value of the latter function variables (because it will not be go to reclaim memory, the cache will always be there).

Guess you like

Origin www.cnblogs.com/jalja/p/11774458.html