Home > Article > Backend Development > Dynamic creation and destruction mechanism of golang function type
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.
Go language provides built-in func
type, which allows us Create and use function values.
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.
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)
Function value have the same life cycle as variables, they are destroyed when they go out of scope.
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!