Welcome to our comprehensive guide on Go Anonymous Functions! In this lesson, we'll explore the world of functions in Go without explicitly naming them, making our code more flexible and efficient. Let's dive in!
Anonymous functions, also known as lambda functions, are functions defined without a name. They are often used when we need a function temporarily or want to pass a function as an argument to another function.
// Simple anonymous function example
func main() {
// Define an anonymous function
add := func(x, y int) int {
return x + y
}
// Using the anonymous function
result := add(5, 3)
fmt.Println(result) // Output: 8
}š Note: In the example above, we defined an anonymous function add inside the main function. The function takes two integers, x and y, and returns their sum.
Anonymous functions provide several benefits:
Anonymous functions can also take multiple parameters:
func main() {
// Define an anonymous function with multiple parameters
greet := func(name string, age int) {
fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
}
// Using the anonymous function
greet("John", 25)
}Anonymous functions can also return values:
func main() {
// Define an anonymous function that returns a square of a number
square := func(num int) int {
return num * num
}
// Using the anonymous function
result := square(4)
fmt.Println(result) // Output: 16
}One of the most powerful features of anonymous functions is the ability to pass them as arguments to other functions:
func applyOperation(x int, operation func(int) int) int {
return operation(x)
}
func main() {
// Define anonymous functions for addition and multiplication
add := func(num int) int {
return num + 5
}
multiply := func(num int) int {
return num * 2
}
// Using anonymous functions as arguments
fmt.Println(applyOperation(3, add)) // Output: 8
fmt.Println(applyOperation(3, multiply)) // Output: 6
}What is the purpose of using anonymous functions in Go?
Embrace the power of Go Anonymous Functions, and let's continue mastering the Go language together! š
Happy Coding! š©āš»šØāš»