In Go, functions are first-class citizens, meaning you can assign them to variables, pass them as arguments to other functions, or return them from functions. This makes Go a powerful language for functional programming techniques. In this article, we'll delve into how you can pass functions as arguments in Go, starting from basic to more advanced examples.
Basic Example
Before passing a function as an argument, let’s see how you can define and call a simple function in Go.
package main
import "fmt"
func sayHello() {
fmt.Println("Hello, World!")
}
func main() {
sayHello()
}
This program defines a function sayHello that prints a simple message and calls it in main.
Passing Functions as Arguments
Next, let’s extend it by passing functions as arguments. This is useful when you want to make your functions more general and reusable.
package main
import "fmt"
func sayHello(name string) {
fmt.Printf("Hello, %s!\n", name)
}
func greet(callback func(string), name string) {
callback(name)
}
func main() {
greet(sayHello, "Alice")
greet(sayHello, "Bob")
}
In this example, greet is a higher-order function that takes another function callback and a string name as arguments. It calls the callback function with name. You can see how sayHello is used as an argument function and invoked with different names.
Intermediate Example: Using Anonymous Functions
Go also supports anonymous functions, which you can pass directly as arguments without defining them separately.
package main
import "fmt"
func greet(callback func(string), name string) {
callback(name)
}
func main() {
greet(func(name string) {
fmt.Printf("Hi, %s!\n", name)
}, "Charlie")
greet(func(name string) {
fmt.Printf("Welcome, %s!\n", name)
}, "Dana")
}
Here, we call greet with inline anonymous functions rather than predefined functions. This flexibility allows creating custom behaviors on-the-fly.
Advanced Example: Returning Functions
You can even return functions from other functions, thus enhancing the functional nature of your code.
package main
import "fmt"
func createGreeter(salutation string) func(string) {
return func(name string) {
fmt.Printf("%s, %s!\n", salutation, name)
}
}
func main() {
sayHi := createGreeter("Hi")
sayWelcome := createGreeter("Welcome")
sayHi("Eve")
sayWelcome("Frank")
}
In this advanced example, createGreeter returns a function which uses the captured salutation value. The returned function is called with a name, resulting in customized greeting messages.
Conclusion
Passing functions as arguments offers flexibility and modularity to Go programs. By mastering this technique, you can write cleaner and more reusable code.