Go Anonymous Functions
An anonymous function is a function without a name. It is defined inline and either called immediately or stored in a variable for later use. Anonymous functions are useful for short, one-off operations that do not need to be reused elsewhere in the code.
Basic Anonymous Function
package main
import "fmt"
func main() {
greet := func(name string) {
fmt.Println("Hello,", name)
}
greet("Alice") // Hello, Alice
greet("Bob") // Hello, Bob
}
The function is stored in the variable greet and called like a regular function.
Anonymous Function Diagram
greet := func(name string) {
│ │ │
│ │ └── parameter
│ └─────────── function body with no name
└──────────────────── stored in variable greet
greet("Alice") → calls the stored anonymous function
Immediately Invoked Function
An anonymous function can be defined and called in the same statement by adding () at the end.
package main
import "fmt"
func main() {
func(msg string) {
fmt.Println(msg)
}("This runs immediately!")
}
Output:
This runs immediately!
Anonymous Function with Return Value
package main
import "fmt"
func main() {
multiply := func(a, b int) int {
return a * b
}
result := multiply(6, 7)
fmt.Println(result) // 42
}
Passing Anonymous Functions as Arguments
Functions are first-class values in Go. An anonymous function can be passed directly into another function.
package main
import "fmt"
func applyTwice(value int, operation func(int) int) int {
return operation(operation(value))
}
func main() {
result := applyTwice(3, func(n int) int {
return n * 2
})
fmt.Println(result) // 12 (3 * 2 = 6, then 6 * 2 = 12)
}
Returning an Anonymous Function
A function can return another function. The returned function is anonymous.
package main
import "fmt"
func makeAdder(x int) func(int) int {
return func(y int) int {
return x + y
}
}
func main() {
addFive := makeAdder(5)
fmt.Println(addFive(3)) // 8
fmt.Println(addFive(10)) // 15
}
Key Points
- Anonymous functions have no name and are defined inline
- They can be stored in variables and called just like named functions
- Adding
()at the end immediately invokes the function after defining it - Anonymous functions can be passed as arguments or returned from other functions
- They form the basis for closures, which is the next topic
