Home »
Golang
Go Anonymous Function
Last Updated : July 21, 2025
In Go, an anonymous function is a function without a name. These functions are useful for quick, short-lived logic and are often used as function values, goroutines, or in closures.
What is an Anonymous Function?
An anonymous function is a function defined without being bound to an identifier (name). These functions can be assigned to variables and invoked later, or invoked immediately where defined.
Syntax
Here is the syntax to define an anonymous function:
func(parameters) returnType {
// function body
}
Assigning an Anonymous Function to a Variable
You can assign an anonymous function to a variable and call it later using that variable.
Example
The following example shows how to define and use an anonymous function in Go by assigning it to a variable and calling it:
package main
import "fmt"
func main() {
greet := func(name string) {
fmt.Println("Hello", name)
}
greet("John")
}
When you run the above code, the output will be:
Hello John
Immediately Invoked Anonymous Function
You can also define and invoke an anonymous function at the same time.
Example
The following example demonstrates an anonymous function in Go that is defined and invoked immediately with arguments:
package main
import "fmt"
func main() {
func(a, b int) {
fmt.Println("Sum:", a+b)
}(5, 7)
}
When you run the above code, the output will be:
Sum: 12
Anonymous Function as Return Value
You can return an anonymous function from another function to create closures or encapsulated logic.
Example
The following example illustrates how a closure in Go can capture a variable from its surrounding scope to create a specialized function:
package main
import "fmt"
func multiplier(factor int) func(int) int {
return func(n int) int {
return n * factor
}
}
func main() {
double := multiplier(2)
fmt.Println(double(5)) // Output: 10
}
When you run the above code, the output will be:
10
Use Cases of Anonymous Functions
- Quick utility logic that doesn’t require reuse.
- Creating closures that retain access to outer variables.
- Passing inline functions to higher-order functions or goroutines.
Exercise
Test your understanding of anonymous functions in Go.
- What is an anonymous function?
- How can an anonymous function be used?
- Which of these is a benefit of anonymous functions?
Advertisement
Advertisement