Golang Code

Anonymous Functions (aka Closures)

· 129 words · 1 minute read #anonymous #closure #func #function #lambda #message

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 could 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 encapulating 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 pass it into the execution parenthesis at the end.

package main

import "fmt"

func main() {

    message := "Hello golangcode.com readers!"

    func(m string) {
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.

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!