Menu
Coddy logo textTech

Anonymous Functions

Lesson 9 of 19 in Coddy's Functions and Pointers in Golang course.

What we've already learned is how to define a function with a name, and when we need to call it, we use that name. However, there is another type of function without names, and we call this type an anonymous function.

It acts just like a simple function but with some differences in how it works. These functions allow us to define actions directly without needing to define a function elsewhere.

Let's look at an example of how to define an anonymous function:

b := func(x, y int) int { return x - y }
fmt.Println(b(100, 50))

Here we define a variable b that stores an anonymous function that performs subtraction. When we call the function, we simply use the variable name b(100, 50).

We can also receive an anonymous function as a result from another function. For example:

func operation(a int) func(int) int {
    if a == 1 {
        return func(a int) int { return a + 10 }
    } else {
        return func(a int) int { return a * 10 }
    }
}
func main() {
    b := operation(1)
    fmt.Println(b(14))
}

Here we define a regular function called operation, and the result (the returned value) will be an anonymous function <strong>func(int) int</strong> instead of a simple value.

We assign the return value to a variable b. Because we pass 1 as a parameter to the function operation, the block that will be executed is this one:

return func(a int) int { return a + 10 }

Now when we call our anonymous function b, we need to pass an integer value, for example, 14.

The result will be:

24

This is the calculation of a + 10 where we pass a which is 14(<strong>b(14)</strong>).
 

challenge icon

Challenge

Easy

Write an anonymous function that takes three integer arguments.

If the first argument is greater than the last one, return the sum of all arguments. If not, return the multiplication of the first and last arguments.

Store the result of the function inside a variable called result.

Try it yourself

package main

import "fmt"

func main() {
    // Define the anonymous function and assign it to a variable called "result".
 
    
    
    // Print the result Don't change this!
    fmt.Println("Result:", result(2, 3, 4))
    fmt.Println("Result:", result(8, 3, 4))
}

All lessons in Functions and Pointers in Golang