Introducing Lambda Functions Using Google's Go
Colin Wilcox MBA
Director / Director of Engineering / Head of Software Engineering / Engineering Manager/ Agile Leader
In Go, a lambda function is an anonymous function that can be defined inline and passed around as a value. Lambda functions in Go are often used for tasks like callbacks, short-lived operations, or closures. In Go, lambda functions are defined using the func keyword without a name.
Defining a Lambda Function
A lambda function can be defined and immediately invoked or assigned to a variable for later use. Looking at the example below:
package main
import "fmt"
func main() {
// Define and immediately invoke a lambda function
result := func(a, b int) int {
return a + b
}(3, 4)
fmt.Println("The result is:", result) // Output: The result is: 7
}
Assigning a Lambda Function to a Variable
You can also assign a lambda function to a variable and then use it later:
package main
import "fmt"
func main () {
// Assign a lambda function to a variable
add := func(a, b int) int {
return a + b
}
// Use the lambda function
fmt.Println("Sum:", add(5, 6)) // Output: Sum: 11
}
Using Lambda Functions as Parameters
Lambda functions can be passed as arguments to other functions:
package main
import "fmt"
// A function that accepts a lambda function as a parameter
func operate(a, b int, op func(int, int) int) int {
return op(a, b)
}
func main() {
// Define a lambda function
multiply := func(a, b int) int {
return a * b
}
// Pass the lambda function to another function
result := operate(3, 4, multiply)
fmt.Println("The result is:", result) // Output: The result is: 12
}
Closures in Lambda Functions
Lambda functions in Go can capture and access variables from their surrounding scope. This is called a closure.
Example:
package main
import "fmt"
func main () {
x:=10
// Define a lambda function that captures 'x'
increment := func() int {
x++
return x
}
fmt.Println(increment()) // Output: 11
fmt.Println(increment()) // Output: 12
}
领英推荐
Key Points
Lambda functions are a powerful feature in Go, allowing you to write concise and flexible code.
Key Advantages Over Regular Language Functions
Lambda functions are defined in a single line and are typically used for small, simple operations.Example: lambda x: x + 1Use Case: When you need a quick, throwaway function that is used only once or twice, such as in a map, filter, or sorted function.
Lambdas can be defined and used inline, making them ideal for short operations in places where defining a full function would feel cumbersome.
For simple operations, lambda functions can make code more readable by keeping the logic where it is used, avoiding unnecessary indirection.
Lambda functions do not need names, which is useful when the function is used only once or is part of a higher-order function call. This can reduce namespace pollution.
Lamba Limitations Do Exist!