In Go, anonymous functions (also known as function literals) are functions that do not have a name. They are often used to create concise and flexible pieces of code that can be passed around as values, facilitating code reuse and modularity. This guide explores the use of Go's anonymous functions, including their syntax, practical examples, and benefits for code reuse.
An anonymous function in Go is defined inline, without a name. It can be immediately invoked or assigned to a variable.
Syntax:
Explanation:
func(a, b int) int { ... }
is the anonymous function.(10, 20)
immediately invokes the function with arguments 10
and 20
.Anonymous functions can be used as arguments to other functions, enabling flexible and reusable code.
Example: Sorting with Anonymous Functions
Explanation:
sort.Slice
takes a slice and a less function that defines the sorting order.func(i, j int) bool { ... }
provides the sorting logic.Anonymous functions can capture variables from their surrounding scope, creating closures that retain state.
Example: Incrementing a Counter
Explanation:
count
and returns another anonymous function that increments and returns it.count
across calls.Anonymous functions are useful for defining handlers or callbacks in a concise manner.
Example: HTTP Request Handler
Explanation:
http.HandleFunc
uses an anonymous function as the handler for HTTP requests to the root path.Go's anonymous functions are a powerful feature for creating concise, flexible, and reusable code. By allowing you to define functions inline, capture variables, and pass functions as values, anonymous functions facilitate better code management and modularity. Understanding how to effectively use anonymous functions can enhance your ability to write clean and efficient Go code.