Anonymous Functions
In this page:
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
package main
import "fmt"
func main() {
square := func(n int) int {
return n * n
}
fmt.Println(square(7))
}
Login to try C/C++/Java/PHP code in the editor
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
package main
import "fmt"
func main() {
result := func(a, b int) int {
return a + b
}(3, 4)
fmt.Println(result)
}
Login to try C/C++/Java/PHP code in the editor
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
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)
}
Login to try C/C++/Java/PHP code in the editor
- 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).
- Forgetting to add '()' after an anonymous function literal to actually invoke it immediately (an IIFE), leaving it just defined but never called.
- Overusing deeply nested anonymous functions where a small named function would be far more readable.
- 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: