ProgramGuru

Anonymous Functions

Start with Anonymous Functions

An anonymous function is a function value written without a declared name. It can be stored in a variable or invoked immediately.

What you’ll learn

  • Explain the main purpose of anonymous functions.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

A function literal begins with func followed by its parameter list, optional results and body. For example, double := func(n int) int { return n*2 } defines a function value. Later code calls it using double(5).

Anonymous functions are useful for short local behavior, callbacks and closures. If a function is long or used in many places, a named declaration is generally easier to read.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for anonymous functionsA function can be a value that you call later.Create function literalStep 1Store as doubleStep 2Call double(7)Step 3Receive 14Step 4A function can be a value that you call later.
A function can be a value that you call later.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	double := func(n int) int { return n * 2 }
	fmt.Println("Double:", double(7))
	result := func(a, b int) int { return a + b }(3, 4)
	fmt.Println("Immediate:", result)
}

Output

Double: 14
Immediate: 7

Trace what the program does

The function literal assigned to double is called later with 7 and returns 14. The second literal is immediately invoked with 3 and 4; its return value 7 is stored in result.

Avoid common mistakes

  • Function literals use the same parameter and return syntax as named functions.
  • Do not assume a function literal runs when it is assigned; add parentheses and arguments to call it.

Try it yourself

Create an anonymous function named isEven that accepts an integer and returns a boolean.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What does func(a,b int) int { return a+b }(3,4) do?
Choose one answer. You can try again.

Answer and explanation

Creates and immediately calls a function

Correct. The function literal assigned to double is called later with 7 and returns 14.

What you should remember

You have practiced Anonymous Functions in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Closures →