Golang: Closure

By Xah Lee. Date: . Last updated: .

Golang's function is a Closure. Practically, a function with local state.

package main

import "fmt"

// return a closure
func ff() func(int) int {
	var i = 0

	var gg = func(x int) int {
		i += x
		return i
	}

	// the returned function gg
	return gg
}

func main() {
	var hh = ff()

	fmt.Println(hh(1)) // 1
	fmt.Println(hh(1)) // 2
	fmt.Println(hh(1)) // 3

}

golang function

Golang

Compile and Run

String

Types and Values

Branching and Loop

Data Structure

Function

Misc

Examples

Reference