Functions

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.


Syntax
//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
    }
}

Notes

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


Example
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
Related

Function Literals

Add to Slack

< Function Literal   |   Methods >

© 2018 SyntaxDB. All Rights Reserved.