golang

Golang Anonymous Function

An anonymous refers to a function that does not have a name. This type of function is also known as a function literal or a lambda function in other programming languages.

Go allows you to create in-line or anonymous functions for short-term use as we will show in this tutorial.

Golang Declare Anonymous Function

We can declare an anonymous function in Go the same way we would when declaring a normal function.

For example, the code below creates an anonymous function inside the main function.

package main
import "fmt"
func main() {
        func() {
                fmt.Println("I don't have a name")
        }
}

Golang Invoke Anonymous Function

Once we declare an anonymous function, we can invoke immediately, as shown in the example below:

package main
import "fmt"
func main() {
        func() {
                fmt.Println("I don't have a name")
        }() // invoke func
}

The above code should execute the code inside the anonymous function and return the string as:

$ go run anonymous_functions.go
I don't have a name

Golang Anonymous Function Assign Variable

We can also assign an anonymous function to a variable and call it using the variable name. Consider the example below:

package main
import "fmt"
func main() {
        str := func() {
                fmt.Println("Hi")
        }
        str()
}

In the example above, we create a variable called “str” and assign it to an anonymous function. We can the use the variable name to call the function.

Golang Pass Arguments to Anonymous Function

Like a typical function in Go, we can pass any number of arguments (of any type) to an anonymous function as shown in the example code below:

package main
import "fmt"
func main() {
        func (a float64)  {
                fmt.Printf("Result: %f", a*3.141)
        }(7.0)
}

In the example above, we pass an argument of type float64 to an anonymous function. Once we call the function, we pass the require argument.

The code above returns:

Result: 21.987000

Golang Return Anonymous Function from Another Function

Go also allows you to return an anonymous function from another function. An example is as shown in the code below:

package main
import "fmt"
func main() {
        anon_func := func() func(x int) {
                result := func(x int) {
                        fmt.Println("Result: ", x)
                }
                return result
        }

        y := anon_func()
        y(2)
}

The above code returns 2.

Conclusion

This guide takes you through the basics of working with anonymous functions in the Go programming language.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list