Anonymous Function in Go: What It Is and How to Use It
anonymous function in Go is a function without a name that can be defined and used inline. It is often assigned to a variable or called immediately, allowing flexible and concise code.How It Works
Think of an anonymous function as a quick recipe you write down and use right away without giving it a formal title. In Go, you can create a function without naming it, which means you can define what it does right where you need it. This is useful when the function is simple or used only once.
Anonymous functions can be stored in variables, passed as arguments to other functions, or executed immediately. This flexibility is like having a tool you can grab and use instantly without having to label it first.
Example
This example shows an anonymous function assigned to a variable and then called to add two numbers.
package main import "fmt" func main() { add := func(a int, b int) int { return a + b } result := add(3, 4) fmt.Println("Sum:", result) }
When to Use
Use anonymous functions when you need a small piece of code that you don't want to reuse elsewhere, like a quick calculation or a callback. They are handy in situations like sorting, filtering, or handling events where defining a full named function would be unnecessary.
For example, when you want to run a function immediately or pass a function as an argument to another function, anonymous functions keep your code clean and focused.
Key Points
- Anonymous functions have no name and can be defined inline.
- They can be assigned to variables or called immediately.
- Useful for short, one-time tasks or callbacks.
- Help keep code concise and readable.