Golang Anonymous Function Explained with Examples

Learn anonymous functions in Go: function literals, immediate calls, parameters and return values, variables, callbacks, closures, goroutines, and common mistakes like loop capture.

Published

Updated

Read time 7 min read

Reviewed byDeepak Prasad

Golang Anonymous Function Explained with Examples

An anonymous function in Go is a function literal: a func with a body (and optional parameters and results) but no name after func. You can run it once, store it in a variable, pass it like any other value, return it from a function, or start it with go—the same declaration and call rules apply as for ordinary named functions in the same package; only the binding is usually local. This page walks from immediate invocation through variables, arguments, closures, and goroutines, then lists mistakes beginners hit.

Tested on: recent Go on 64-bit Linux.


Quick answer: anonymous function in Go

An anonymous function has no name. To define and call it in one step, add () after the literal:

go
package main

import "fmt"

func main() {
	func() {
		fmt.Println("hello")
	}()
}
Output

You should see hello. Without the final (), you only build a function value—you must call it, assign it, or pass it somewhere. Anonymous functions are handy for short inline logic, callbacks, closures, and go func() { ... }().


What is an anonymous function in Go?

The Go spec calls this form a function literal. Colloquially people say anonymous function or inline function.

Named function at package level:

go
func greet() { /* ... */ }

Function literal (no name after func):

go
func() { /* ... */ }

Use a literal when the logic is small, local to one place, or you need a function value (argument, return, or closure). Prefer a named function when the same behavior is reused, long, or should appear in package API docs.


Call an anonymous function immediately

Write the literal, then () to invoke it—sometimes called an immediately invoked function expression (IIFE).

Form Meaning
func() { ... } Builds a function value
func() { ... }() Builds it and calls it now

Parameters

Arguments go in the trailing parentheses:

go
package main

import "fmt"

func main() {
	func(name string) {
		fmt.Println("hi,", name)
	}("golinuxcloud")
}
Output

Return value

You can take the result of an immediate call:

go
package main

import "fmt"

func main() {
	n := func(a, b int) int {
		return a + b
	}(10, 20)
	fmt.Println(n)
}
Output

You should see 30. If the expression gets long, switch to a named helper for readability.


Assign an anonymous function to a variable

In Go, functions are values. Assign the literal to a variable, then call it like a normal function:

go
package main

import "fmt"

func main() {
	add := func(a, b int) int {
		return a + b
	}
	fmt.Println(add(2, 3))
}
Output

You should see 5. The variable holds a function value; it can be reassigned or passed onward like other values.


Pass an anonymous function as an argument

Pass a literal where a function type is expected—common for small predicates or callbacks:

go
package main

import "fmt"

func apply(n int, f func(int) int) int {
	return f(n)
}

func main() {
	out := apply(4, func(x int) int {
		return x * x
	})
	fmt.Println(out)
}
Output

You should see 16. For the same logic used in many places, a named function type or named function is often clearer.


Return an anonymous function from another function

A function can return a function value. The inner literal often captures outer parameters or locals—that is the usual closure shape:

go
package main

import "fmt"

func multiplier(n int) func(int) int {
	return func(x int) int {
		return x * n
	}
}

func main() {
	times3 := multiplier(3)
	fmt.Println(times3(4))
}
Output

You should see 12.


Anonymous function and closure

Term Meaning
Function literal Spec name for func(...) ... { }
Anonymous function Informal: no name after func
Closure Function value that uses variables from an enclosing scope
Inline function Informal: defined at the point of use

Not every literal is a closure in the interesting sense: func() { fmt.Println(1) }() does not capture outer variables. A literal that reads or writes n from an outer stack frame is a closure. For more patterns, see closures in Go.

go
package main

import "fmt"

func main() {
	n := 0
	next := func() int {
		n++
		return n
	}
	fmt.Println(next(), next())
}
Output

You should see 1 and 2 on one line. Be careful capturing pointers or maps if you need clear ownership.


Anonymous function with a goroutine

For background work and scheduling patterns beyond literals, see Goroutines in Go.

Start background work with go and a literal; the final () still starts the call (in a new goroutine):

go
go func() {
	// work
}()

Pass data in as parameters so the goroutine does not depend on a changing outer variable—especially inside loops:

go
package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	var wg sync.WaitGroup
	words := []string{"a", "b", "c"}
	for _, w := range words {
		wg.Add(1)
		go func(s string) {
			defer wg.Done()
			fmt.Println(s)
			time.Sleep(10 * time.Millisecond)
		}(w)
	}
	wg.Wait()
}
Output

You should see three lines with a, b, and c in some order. Writing go func() { fmt.Println(w) }() without passing w can print the wrong value because the loop variable is shared; always pass the value you need (or copy inside the loop body before go).


Anonymous Function vs Named Function

Use an anonymous function when the logic is short, local, and only needed at one place. Use a named function when the logic is reused, complex, or important enough to deserve its own name.

For declaring normal package-level functions with names, parameters, return values, and documentation, see Functions in Go.

Situation Better choice Why
Function is reused across the package Named func Easier to call, test, and document
Function body is long or has multiple branches Named func Improves readability
Logic is small and used only once Anonymous function Keeps the logic close to where it is used
Function is passed as a callback Anonymous function Avoids creating a separate function for one call site
Goroutine needs local values Anonymous function Common pattern with go func(...) { ... }()
Function needs clear documentation Named func A named function explains intent better
Function captures nearby variables Anonymous function / closure Useful when the behavior depends on local state

A good rule is:

text
Use anonymous functions for small local behavior.
Use named functions when the logic deserves a name.

Anonymous Function, Closure, and Lambda

In Go, the official term is function literal. In normal tutorials, this is usually called an anonymous function because the function has no name.

People coming from other languages may also call this a lambda, but Go does not have a lambda keyword.

These terms are related, but not exactly the same:

Term Meaning in Go
Anonymous function A function without a name
Function literal Official Go term for anonymous function syntax
Closure A function that uses variables from the surrounding scope
Lambda Informal term from other languages; not a Go keyword

An anonymous function becomes a closure when it captures and uses variables from the outer scope.

Example idea:

text
anonymous function = function has no name
closure = function remembers or uses outer variables

So all closures are function values, but not every anonymous function needs to capture outer state.


Common mistakes with anonymous functions

Omitting the call

func() { } alone does not run; add () or assign and call.

Loop variable capture in go func()

Capture the iteration value as a parameter (see the goroutine example above).

Huge inline bodies

If the literal needs many comments or branches, extract a named function.

Overusing IIFEs

Plain statements or a small block are enough unless you need a scope boundary or defer tied to a short lifetime.


Go anonymous function cheat sheet

Goal Pattern
Literal only func() { ... }
Invoke now func() { ... }()
With args func(x int) { ... }(42)
With result v := func() int { return 1 }()
Store and call f := func() { ... }; f()
Pass in run(func() { ... })
Return return func() int { return n }
Goroutine go func() { ... }()
Safe loop + go go func(v T) { ... }(v)

Which pattern should you use?

You need… Use
Run setup once in a narrow scope IIFE func() { ... }()
Behavior passed once Literal argument
Stateful counter / factory Return a literal that closes over locals
Background work go func() { ... }() with parameters as needed

Summary

An anonymous function in Go is a function literal: func plus signature and body, without a name. Trailing () runs it immediately; omitting () leaves a value you can assign, pass, or return. Literals that capture outer variables are closures. With goroutines, pass loop values into the literal’s parameters to avoid classic capture bugs. Use named functions when the logic grows or is shared widely; use literals for small, local behavior and callbacks.

Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …