Go closure function example

In this example, we will show you how to create a closure in Go with an example.

A closure in Go is an anonymous function returned from an enclosing function. Closure retains a reference to a variable defined outside its body.

Go closure function example

In the example, we will create intSeq() function, which generates a sequence of integers. It returns a closure which increments the i variable.


package main

import "fmt"

func intSeq() func() int {

    i := 0
    return func() int {
        i++
        return i
    }
}

func main() {

    nextInt := intSeq()

    fmt.Println(nextInt())
    fmt.Println(nextInt())
    fmt.Println(nextInt())
    fmt.Println(nextInt())

    nextInt2 := intSeq()
    fmt.Println(nextInt2())
}

Output:

1
2
3
4
1

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course