Can Functions Be Passed as Parameters in Go?
Java allows passing functions as parameters through the use of anonymous inner classes. Does Go provide a similar mechanism to facilitate this functionality?
Answer:
Absolutely! Go supports passing functions as parameters through anonymous functions and closures. Here are a few examples:
Example 1:
package main import "fmt" type convert func(int) string func value(x int) string { return fmt.Sprintf("%v", x) } func quote123(fn convert) string { return fmt.Sprintf("%q", fn(123)) } func main() { result := quote123(value) fmt.Println(result) // Output: "123" }
In this example, the convert function type is defined to take an integer and return a string. The value function implements convert by returning the string representation of the input integer. The quote123 function accepts a convert function as an argument and returns a quoted string representation of the result of calling the function with the value 123.
Example 2:
package main import "fmt" func main() { result := quote123(func(x int) string { return fmt.Sprintf("%b", x) }) fmt.Println(result) // Output: "1111011" }
Here, an anonymous function is passed as an argument to the quote123 function. The anonymous function converts the input integer into its binary string representation.
Example 3:
package main import "fmt" func main() { foo := func(x int) string { return "foo" } result := quote123(foo) fmt.Println(result) // Output: "foo" }
In this case, a named function, foo, is passed as an argument to quote123. The foo function simply returns the string "foo" for any input.
These examples demonstrate the flexibility and power of passing functions as parameters in Go, enabling you to create generic and reusable code.
The above is the detailed content of Can Go Functions Be Passed as Parameters?. For more information, please follow other related articles on the PHP Chinese website!