Go Anonymous Function Explained [Practical Examples]

In this article, we will discussing about golang anonymous function with an help of examples.

 

What are anonymous functions in golang?

In Golang, Anonymous function are special function created without the function name.It is useful when someone want to create an inline function.It can accept input and return output just like the standard function does. It is also known as function literal or lambda function

Advertisement

For Example of anonymous function.

func (){}

Explanation

The above example works just like any other regular function in golang.Its simply a valid function.

 

Declaring anonymous function in Go

It is declared the same way as normal function. For example, Anonymous function in main function in go

package main
import "fmt"
func main() {
        func() {
                fmt.Println("sample of Anonymous function without name in GoLinuxCloud")
        }
}

output:-

$ go run main.go
sample of Anonymous function without name in GoLinuxCloud

Explanation:

Advertisement

Here we define function without name by using syntax func (){...} and we can execute the program using go run main.go to see the output on terminal.

  • To define the function, use the syntax: func (){...}
  • To define and execute the function by adding parentheses at the end. use the syntax: func (){...}()

 

Invoking anonymous function in Go

Anonymous function can be invoked immediately after declaration. They are invoked by use of parentheses at the end of function,func (){...}() .

Example of invoking anonymous function

package main
import "fmt"
func main() {
        func() {
                fmt.Println("sample of invoking Anonymous function without name in GoLinuxCloud.")
        }() // <- invoke func
}

Output:-

$ go run main.go
sample of invoking Anonymous function without name in GoLinuxCloud.

Explanation:-

The above program executes and returns a string of values from an anonymous function.

 

Use variable to execute anonymous function

Golang makes it easy to work with anonymous functions by assigning them to a variable. This variable is used to call the function later in the program.

Example: Go Anonymous Function

package main
import "fmt"

func main() {
  // anonymous function
  var displayMessage = func() {
    fmt.Println(`Hello, Welcome to GoLinuxCloud.`)
  }

  // function call
  displayMessage()

}

Output:-

$ go run main.go
Hello, Welcome to GoLinuxCloud.

Explanation:
Here, we have created a variable called var displayMessage = func(){} and assigned it to an anonymous function and used displayMessage() variable name to call the function.

 

Passing parameters into anonymous function

Anonymous function can accept function parameter like a regular function.
For Example


package main

import "fmt"

func main() {
	// anonymous function
	var sumOfIntegers = func(x, y int64) {
		sum := x + y
		fmt.Printf("Sum  of %d and %d is: %d ", x, y, sum)
	}

	// function call
	sumOfIntegers(9, 4)
}

Output:

Advertisement
$ go run main.go
  Sum  of 9 and 4 is: 13

Explanation:

Here, the anonymous function takes two integer arguments x and y of type int64.

var sumOfIntegers = func(x, y int64) {
		sum := x + y
		fmt.Printf("Sum  of %d and %d is: %d ", x, y, sum)
	}

Since we have assigned the anonymous function to the sumOfIntegers variable, we are calling the function using the variable name.

// function call
	sumOfIntegers(9, 4) 

The values x and y are values passed to the function.

 

Return values from anonymous function in Go

In Go, anonymous function can return values like any other regular function.

For Example

Advertisement
// Program to return value from an anonymous function
package main

import "fmt"

func main() {

	// anonymous function
	var sumOfIntegers = func(x, y int64) int64 {
		add := x + y

		return add
	}

	// function call
	result := sumOfIntegers(9, 4)

	fmt.Println("SumOfIntegers is:", result)

}

Output:

$ go run main.go
SumOfIntegers is: 13

Explanation:

The variable sumOfIntegers has been assigned the anonymous function func(x,y int64) int64 . The function adds two variables of x and y and returns computed results of type int64.

 

More Examples of return value from anonymous function

// Program to return the area of a square
package main

import "fmt"

func main() {

	// anonymous function
	areaOfTriangle := func(length int64) int64 {
		return length * length
	}

	// function call using variable name
	fmt.Println("The area of a square is", areaOfTriangle(4))
}

Output:

$ go run main.go
The area of a square is 16

We have used := shorthand to defined an anonymous function func(length int64) int64{...} and assigned it to the variable areaOfTriangle . The area of the square, length * length , is returned to the area.

Advertisement

 

Pass anonymous function as arguments to other functions in Go

In Go, an anonymous functions can be passed as arguments to other functions. For this scenario, the variable that contains the anonymous function is the one passed. For example,

package main

import "fmt"

// regular function to calculate square of numbers
func CalculateSquareOfNumber(num int64) int64 {
	return num * num
}

func main() {

	// anonymous function that returns sum of numbers
	add := func(x, y int64) int64 {
		return x + y
	}

	// function call
	result := CalculateSquareOfNumber(add(9, 4))
	fmt.Println("Result is:", result)

}

Output:

$ go run main.go
Result is: 169

Explanation:

We have created two functions:

  • add := func(x, y int64) int64 {..} an anonymous function to perform addition of two numbers (x,y)
  • CalculateSquareOfNumber(num int64) int64 {...}a regular function to calculate a square of a number.

result := CalculateSquareOfNumber(add(9, 4)) is a function called inside the main().

Here, we have passed the anonymous function as the function parameter to the CalculateSquareOfNumber() function. The anonymous function returns the addition of two parameters. This add() is then passed to the CalculateSquareOfNumber() function, which returns the square of the added parameters.

Advertisement

 

Return an anonymous function from a function in Go

In Go,an anonymous function can be created and returned from inside a regular function. For example,

// Program to return an anonymous function

package main

import "fmt"

// function that returns an anonymous function
func displayNumber() func() int64 {

	var val int64 = 30
	return func() int64 {
		val++
		return val
	}
}

func main() {

	results := displayNumber()

	fmt.Println("Results from displayNumber function: ", results())

}

Output:

$ go run main.go
Results from displayNumber function:  31

Explanation:

func displayNumber() func() int64 {}:- The func() denotes that displayNumber() returns a function,The int64 denotes that the anonymous function returns an integer 64 bits. Notice that displayNumber() is a regular function and Inside it,we have created an anonymous function.

return func() int {...}:- It is used to return the anonymous function. So, when the displayNumber() function is called, the anonymous function is also called and the incremented of value is returned.

 

Summary

This article will take you through the basics of working with anonymous functions in Go with the practical examples provided.

 

References

Anonymous Functions in Go

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X