Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

1 snippets
  • Example of closures in Golang

    package main
    
    import "fmt"
    
    // The function createCounter returns anonymous function defined within its body.
    // The returned function encapsulates the variable count, creating a closure.
    func createCounter() func() int {
    	count := 0
    
    	return func() int {
    		count++
    
    		return count
    	}
    }
    
    func main() {
        // We invoke createCounter, storing the result (a function) in counter variable.
        // This function captures and retains its own count value,
        // which updates with each subsequent invocation of createCounter.
    	counter := createCounter()
    
    	fmt.Println(counter())
    	fmt.Println(counter())
    	fmt.Println(counter())
    
    	newCounter := createCounter()
    	
        fmt.Println(newCounter())
    }
    
    // $ go run main.go 
    // 1
    // 2
    // 3
    // 1

    A simple example of using closures in Go.