← Back to Go Course | Chapter 4: Functions | Lesson 5 of 7

Anonymous Functions

An anonymous function is a mini recipe with no name, written right where you need it, used once and thrown away -- or handed to someone else to use later.

Defining and Calling an Anonymous Function

A function literal omits a name and can be assigned to a variable, which is then called just like any regular function using that variable name followed by parentheses.

Example: Defining and Calling an Anonymous Function

markup
package main

import "fmt"

func main() {
	square := func(n int) int {
		return n * n
	}
	fmt.Println(square(7))
}

Immediately Invoked Function Literals

An anonymous function can be called the instant it's defined by appending arguments in parentheses right after its closing brace, useful for scoping a one-off block of logic.

Example: Immediately Invoked Function Literals

markup
package main

import "fmt"

func main() {
	result := func(a, b int) int {
		return a + b
	}(3, 4)
	fmt.Println(result)
}

Anonymous Functions as Arguments

Anonymous functions are frequently passed directly as arguments to other functions that expect a callback, avoiding the need to declare and name a separate function used in only one place.

Note: This pattern is common with sort.Slice, which takes an anonymous comparison function.

Example: Anonymous Functions as Arguments

markup
package main

import (
	"fmt"
	"sort"
)

func main() {
	nums := []int{5, 2, 8, 1}
	sort.Slice(nums, func(i, j int) bool {
		return nums[i] < nums[j]
	})
	fmt.Println(nums)
}
Common Mistakes
  1. Giving an anonymous function assigned to a variable a redundant name inside the func keyword, which Go doesn't allow (func literals have no name).
  2. Forgetting to add '()' after an anonymous function literal to actually invoke it immediately (an IIFE), leaving it just defined but never called.
  3. Overusing deeply nested anonymous functions where a small named function would be far more readable.
Chapter Summary
  • An anonymous function is a function literal with no name, defined inline where it's used.
  • Anonymous functions can be assigned to a variable and called through it.
  • They can also be invoked immediately after definition by appending () to the literal.
  • They're commonly used as short callback arguments or for goroutines.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.