假设有一个函数 calculate(x int, y int) int
,我们可以使用类型转换将其转换为函数类型 type computeFunc func(int, int) int
。
示例代码:
package main
import (
"fmt"
)
func calculate(x int, y int) int {
return x + y
}
type computeFunc func(int, int) int
func main() {
// 将 calculate 函数转换为 computeFunc 类型
var compute computeFunc = calculate
// 使用 compute 调用 calculate 函数
result := compute(3, 4)
fmt.Println(result) // 输出 "7"
}
在代码中,我们首先定义了函数 calculate
,它接受两个整数参数并返回它们的和。
然后,我们定义了一个新的类型 computeFunc
,它代表了一个接受两个整数参数并返回一个整数的函数类型。
接着,我们在 main
函数中使用类型转换将 calculate
函数转换为 computeFunc
类型,并将其赋值给变量 compute
。
最后,我们使用 compute
变量调用 calculate
函数,并将结果打印到控制台。