Closures in Go

Closures are functions which enclose other functions, often with a function return type. The inner functions are able to reference the variables around the closure function.

//like regular functions, parameters are optional
function closureFunctionName(paramName dataType) func(returnType) {
    var closureVar dataType
    return func(paramName dataType) (returnVarName returnType) {
        closureVar = value //inner functions can access outer closure variables
        return value //if necessary


Inner functions are most often anonymous functions (or function literals).

import "fmt"

func square(x int) func() int {
    return func() int { //anonymous function
        x = x * x
        return x

func main() {
    fmt.Println("2 squared is: ", square(2))

See Also

Function Literals

Add to Slack

< Function Literal   |   Methods >

© 2019 SyntaxDB. All Rights Reserved.