41. Go - Closure

Code blocking code to limit scope.

Code blocking with curly brackets.


Example:

package main

import "fmt"

func main() {
    x := 5
    fmt.Println(x)

    {
        y := 10
        fmt.Println(y)
    }
}


Example 2:

package main

import "fmt"

func plus() func() int {
    var x int
    return func() int {
        x++
        return x
    }
}

func main() {
    test := plus()
    test2 := plus()
    fmt.Println(test())
    fmt.Println(test())
    fmt.Println(test2())
    fmt.Println(test2())
}


Return Function with inner closure scope:

package main

import "fmt"

func printerr() func() int {
    x := 0

    return func() int {
        x++
        return x
    }
}

func main() {
    test1 := printerr()
    fmt.Println(test1())
    test2 := printerr()
    fmt.Println(test2())

    fmt.Println("TWO")
    fmt.Println(test2())
    fmt.Println(test2())
    fmt.Println(test2())
    fmt.Println(test2())

    fmt.Println("ONE")
    fmt.Println(test1())

}

// test1 is a printerr function with its own scope of x variable.

// test2 cannot access test1's variable x

Comments

Popular posts from this blog

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

20. Data Analytics - Analyze Data to Answer Questions - Week 1

3. Algorithms - Selection Sort