Anonymous Functions (aka Closures)

· 234 words · 2 minutes read

Here is a basic example of how an anonymous function, or lambda function, can be used with Go. We’re just printing a statement to screen, but it can be used for various things - one of which can be just to segment code which will only need to get run once and doesn’t need to be referenced.

It also has the use case of encapsulating the variables used within itself, so only from within are you able to access a variable from within. Once the function has finished the variables can then be garbage collected. To pass data into the function we have to add it to the execution parenthesis at the end.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package main

import "fmt"

func main() {

    message := "Hello golangcode.com readers!"

    func(m string) {
        fmt.Println(m)
    }(message)
}

using an anonymous function in go

This technique is especially useful in Go, because once you have this structure, you can turn it into a goroutine by simple adding the word go before your func.

This is also possible:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package main

import "fmt"

func main() {
    message := "Hello golangcode.com readers!"
    func() {
        fmt.Println(message)
    }()
}

This is not possible:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package main

import "fmt"

func main() {
    func() {
        message := "Hello golangcode.com readers!"
    }()
    fmt.Println(message)
}

an error when using an anonymous function incorrectly

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!