Home  >  Article  >  Backend Development  >  Dynamic creation and destruction mechanism of golang function type

Dynamic creation and destruction mechanism of golang function type

王林
王林Original
2024-04-28 15:12:011136browse

The Go language provides the func type for dynamic creation and destruction of function values: Creation: Use the func keyword to dynamically create a function type, such as f := func(x int) int { return x * x }. Call: Pass a function value as a parameter to another function, such as call(f, 5). Destruction: Function values ​​are destroyed when they go out of scope, similar to variables.

Dynamic creation and destruction mechanism of golang function type

Dynamic creation and destruction mechanism of function types in Go language

Go language provides built-in func type, which allows us Create and use function values.

Dynamic creation of function types

You can use the func keyword to dynamically create a function type:

f := func(x int) int {
    return x * x
}

The above code creates a function type that accepts Takes an integer argument and returns an integer.

Dynamic call function value

You can call a function value by passing it as a parameter to another function:

func call(f func(int) int, x int) {
    fmt.Println(f(x))
}

call(f, 5)

Destroy function value

Function value have the same life cycle as variables, they are destroyed when they go out of scope.

Practical case: dynamically create a callback function

Creating a callback function in a goroutine to process the results is a common scenario:

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    resultCh := make(chan int)

    // 创建回调函数
    f := func(result int) {
        resultCh <- result
    }

    go func() {
        // 模拟耗时的处理
        time.Sleep(5 * time.Second)
        result := 42
        f(result)
    }()

    select {
    case result := <-resultCh:
        fmt.Println("Received result:", result)
    case <-ctx.Done():
        fmt.Println("Timed out waiting for result")
    }
}

In this example, the dynamically created callback Function f is used to notify the main goroutine of the result after the goroutine completes processing.

The above is the detailed content of Dynamic creation and destruction mechanism of golang function type. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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