Golang - Chapter 5

Functions & Closures in Go

Function Declarations

Functions can take 0 or more arguments and parameter types come after the parameter name.

Return types are specified after the closing bracket of the parameters.

func multiply(a int, b int) int {
    return x * y
}

Since both a and b are of the same type, int, we can combine their type declaration into the following:

func multiply(a, b int) int {
    return x * y
}

Returning Multiple Results

Unlike languages like C, in Go, we can return multiple results.

func areaAndPerimeter(length, breadth int) (int, int) {
    return (length * breadth), (length * 2 + breadth * 2)
}

func main() {
    area, perimeter := areaAndPerimeter(15, 20)
}

Note: However, if you only need some of the return values, you may end up with unused variables. In those case, we can ignore some of them by using the _ symbol.

Function Order

init() is a function which you can define to run code before that of themain() function. Also, init() is the only function which you can define multiple times. These init() statements will be run in sequence.

func init() {
	fmt.Println("Init 1")
}
func init() {
	fmt.Println("Init 2")
}
func init() {
	fmt.Println("Init 3")
}

Passing Functions Around

In Go, functions are values as well which means we can pass them around.

func saySomething(fn func(string) string) string {
	return fn("Something")
}

func saySomethingElse(word string) string {
	return word + " Else"
}

func main() {
    // prints "Something Else"
    fmt.Println(saySomething(saySomethingElse))
}

In the above example, we defined a function called saySomething which in turn takes in a function that accepts a string and returns a string.

In the main function, we called saySomething and passed saySomethingElse as a function argument to it.

Closures

What is a closure?

According to this Stack Overflow answer, a closure is a persistent local variable scope. And that is pretty accurate. Essentially, a closure allows us to make references to variables even though the code execution is outside of the block where the variables were defined in.

// a closure with reference to local variable x is returned
func counter() func() int {
	x := 0
    return func() int {
		x++
        return x
    }
}

func main() {
    count := counter() // returns a function
    
    fmt.Println(count()) // prints 1
    fmt.Println(count()) // prints 2
}
comments powered by Disqus

Related