Anonymous Functions in Go

GolangGolangBeginner
Practice Now

Introduction

In the previous experiment, we learned about the use of functions. In Go, there is a special type of function called an anonymous function. It doesn't have a name and is simply referred to as an anonymous function. Let's learn about it together.

Knowledge Points:

  • Defining anonymous functions
  • Using anonymous functions

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Golang`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go(("`Golang`")) -.-> go/DataTypesandStructuresGroup(["`Data Types and Structures`"]) go/FunctionsandControlFlowGroup -.-> go/for("`For`") go/DataTypesandStructuresGroup -.-> go/slices("`Slices`") go/FunctionsandControlFlowGroup -.-> go/range("`Range`") go/FunctionsandControlFlowGroup -.-> go/functions("`Functions`") go/FunctionsandControlFlowGroup -.-> go/closures("`Closures`") go/DataTypesandStructuresGroup -.-> go/pointers("`Pointers`") subgraph Lab Skills go/for -.-> lab-149099{{"`Anonymous Functions in Go`"}} go/slices -.-> lab-149099{{"`Anonymous Functions in Go`"}} go/range -.-> lab-149099{{"`Anonymous Functions in Go`"}} go/functions -.-> lab-149099{{"`Anonymous Functions in Go`"}} go/closures -.-> lab-149099{{"`Anonymous Functions in Go`"}} go/pointers -.-> lab-149099{{"`Anonymous Functions in Go`"}} end

Defining Anonymous Functions

The declaration of an anonymous function is similar to that of a regular function, except for the omission of the function name. It can be assigned to a variable of function type. Let's take a look at its syntax:

// Anonymous function declaration
func(input parameters)(return parameters){
    code block
}

Comparing it to a regular function declaration:

// Regular function declaration
func function name(parameters...)(return values...){
    code block
}

As you can see, the only difference is that the function name is removed for an anonymous function to be used.

Anonymous Functions without Parameters

Let's start with a simple example. Create a new file called anonymous.go and write the following code:

package main

import (
    "fmt"
)

func main() {
    // Define an anonymous function and assign it to the variable f
    f := func() {
        fmt.Println("hello world")
    }
    // Call the variable f
    f()
}

The output will be:

hello world

In this program, we have re-implemented the hello world program using an anonymous function. We define an anonymous function inside the main function and assign it to the variable f. Later, we call the variable f to execute the anonymous function.

Anonymous Functions with Parameters

Anonymous functions can also have parameters. You just need to provide the values when invoking the function. Here's an example:

package main

import (
    "fmt"
)

func main() {
    f := func(s string) {
        fmt.Println(s)
    }
    f("hello world")
}

Anonymous Functions with Return Values

Anonymous functions can also have return values.

Here's an example of an anonymous function that takes two integers as input and returns their sum:

package main

import (
    "fmt"
)

func main() {
    f := func(a, b int) (res int) {
        return a + b
    }
    res := f(3, 5)
    fmt.Println(res)
}

After running the program, you will see that the output is the sum of the two input parameters.

8

Declaring and Assigning Anonymous Functions Simultaneously

We can declare and assign anonymous functions simultaneously. The following program demonstrates this:

package main

import (
    "fmt"
)

func main() {
    // Declare input and output parameters and assign values
    res := func(a, b int) (res int) {
        return a + b
    }(3, 5)
    fmt.Println(res)
}

In this program, we declare and assign an anonymous function on the same line. The assigned parameters are enclosed in parentheses.

Using Anonymous Functions as Callback Functions

Earlier, we assigned an anonymous function to a variable. Similarly, we can also use an anonymous function as an argument to a function. In this case, the anonymous function can be referred to as a callback function.

Let's look at an example:

package main

import (
    "fmt"
    "math"
)

// Traverse the elements of a slice and process each value using a callback function
func visit(lst []float64, f func(float64)) {
    for _, value := range lst {
        f(value)
    }
}

func main() {
    // Sum each element
    arr := []float64{1, 2, 3, 4, 5, 6, 7, 8, 9}
    visit(arr, func(v float64) {
        fmt.Printf("Sum:%.0f ", v+v)
    })
    println()
    // Calculate the product of each element
    visit(arr, func(v float64) {
        fmt.Printf("Product:%.0f ", v*v)
    })
    println()
    // Calculate the square of each element
    visit(arr, func(v float64) {
        v = math.Pow(v, 2)
        fmt.Printf("Square:%.0f ", v)
    })
    println()
}
Sum:2 Sum:4 Sum:6 Sum:8 Sum:10 Sum:12 Sum:14 Sum:16 Sum:18
Product:1 Product:4 Product:9 Product:16 Product:25 Product:36 Product:49 Product:64 Product:81
Square:1 Square:4 Square:9 Square:16 Square:25 Square:36 Square:49 Square:64 Square:81

In this program, we first create a visit function with a callback that iterates over a given slice list and passes the values to the callback function for processing.

Inside the main function, we use an anonymous function to define three different callbacks to calculate the sum, product, and square of each element.

As you can see, callback functions are very flexible. They act as intermediate functions, and different anonymous functions can produce different behaviors within the callback function.

Summary

In this lab, we learned about anonymous functions, a special type of function that doesn't have a name.

To summarize the related knowledge points:

  • Anonymous functions are functions without a name.
  • Anonymous functions can have input and return parameters.
  • Anonymous functions can be assigned to variables or used as parameters in function calls, making them callback functions.

In the next experiment, we will dive deeper into the topic of structs.

Other Golang Tutorials you may like