How to use closure in Go

4 Answers

0 votes
package main

import "fmt"

func makeAdder(x int) func(int) int {
    // This inner function forms a closure.
    // It "remembers" the value of x even after makeAdder returns.
    return func(y int) int {
        return x + y
    }
}

func main() {
    add10 := makeAdder(10) // x = 10 is captured
    result := add10(20)    // y = 20

    fmt.Println(result)
}


/*
run:

30

*/

 



answered 4 hours ago by avibootz
0 votes
// Closures capture variables by reference

package main

import "fmt"

func main() {
    counter := 0

    // Closure capturing "counter" by reference
    inc := func() {
        counter++
    }

    inc()
    inc()

    fmt.Println(counter)
}


/*
run:

2

*/

 



answered 4 hours ago by avibootz
0 votes
// Closures inside loops

package main

import "fmt"

func main() {
    funcs := []func(){}

    for i := 0; i < 3; i++ {
        i := i // create a new variable for this iteration
        funcs = append(funcs, func() {
            fmt.Println(i)
        })
    }

    funcs[0]()
    funcs[1]()
    funcs[2]()
}



/*
run:

0
1
2

*/

 



answered 4 hours ago by avibootz
0 votes
// Closures with parameters

package main

import "fmt"

func main() {
    factor := 3

    multiply := func(a int, b int) int {
        return (a + b) * factor // closure captures "factor"
    }

    fmt.Println(multiply(5, 5))
}



/*
run:

30

*/

 



answered 4 hours ago by avibootz

Related questions

5 answers 3 views
3 answers 12 views
3 answers 15 views
2 answers 149 views
149 views asked Oct 20, 2020 by avibootz
2 answers 269 views
269 views asked Oct 7, 2020 by avibootz
...