Home > Article > Backend Development > Can You Define a Type for Function Calls in Go?
Go keywords such as go and defer expect function calls as parameters. Is there a dedicated type that can serve the same purpose, allowing functions to receive function calls as arguments instead of functions?
Unfortunately, there is no such type in Go. The behavior of go and defer is built into the language specification and enforced by the compiler.
Instead, it's possible to use function values as variables or values. These can be called later as if they were regular functions.
<code class="go">func myFunc() { fmt.Println("hi") } func main() { var f func() f = myFunc f() // This calls the function value stored in f: myFunc in this example }</code>
In some cases, it's desirable to have automatic parameter saving for function calls. For specific function types, this can be achieved by introducing helper functions with identical signatures that return parameterless functions. These closures call the original function with the saved parameters.
Reflection can be used to avoid manual parameter copying. However, it involves passing the function rather than calling it, slowing down the process.
There's an exception when using methods. Method values can save a copy of the receiver, allowing automatic parameter saving for method calls.
<code class="go">type myParams struct { format string i int s string } func (mp myParams) Call() { fmt.Printf(mp.format, mp.i, mp.s) } func main() { p := myParams{format: "%d %q\n", i: 1, s: "Hello, playground"} launch(p.Call) // p is saved here p.i, p.s = 2, "changed" time.Sleep(time.Second) }</code>
Note: None of these approaches provide an exact match for the desired functionality. If the parameters are subject to change, manual copying is necessary before passing the function to a helper that saves the parameters.
The above is the detailed content of Can You Define a Type for Function Calls in Go?. For more information, please follow other related articles on the PHP Chinese website!