Home >Backend Development >Golang >How Does Go Enable Passing Functions as Parameters?
In Java, one can pass functions as parameters using anonymous inner classes, although this can be cumbersome. Go offers a more straightforward approach to this with function types and closures.
Consider the following Go code which implements a convert function type that takes an integer and returns a string value:
type convert func(int) string
The value function satisfies the convert type by returning a string representation of the integer:
func value(x int) string { return fmt.Sprintf("%v", x) }
The quote123 function uses a convert function to convert 123 to a string and quotes the result:
func quote123(fn convert) string { return fmt.Sprintf("%q", fn(123)) }
In the main function, the convert function is used with different implementations of the convert type, including anonymous functions:
result := quote123(func(x int) string { return fmt.Sprintf("%b", x) })
The convert type ensures type safety, requiring that all functions passed to it implement the convert type. This helps maintain code correctness and prevents type errors.
The above is the detailed content of How Does Go Enable Passing Functions as Parameters?. For more information, please follow other related articles on the PHP Chinese website!