Home > Backend Development > Golang > Can You Define a Type for Function Calls in Go?

Can You Define a Type for Function Calls in Go?

Mary-Kate Olsen
Release: 2024-11-01 11:49:02
Original
607 people have browsed it

Can You Define a Type for Function Calls in Go?

Is it possible to 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?

No Direct Type for Function Calls

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.

Using Function Values as Variables

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>
Copy after login

Mimicking Automatic Parameter Saving

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.

Using Reflection to Pass Functions

Reflection can be used to avoid manual parameter copying. However, it involves passing the function rather than calling it, slowing down the process.

Single Exception: Method Values

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template