函数也是一种类型
在go语言中,函数可以自定义为一种类型,因此,函数也可以像其他结构体类型一样,具有自己的方法。
相同的函数签名(指具有相同的参数类型和返回值类型,并且类型个数一致),便可以转换为该函数类型,调用该函数类型的方法。
package main
import (
"fmt"
)
//定义一个函数类型,函数的签名为两个输入参数,分别为int以及string类型,一个返回值string类型
type myfun func(int, string) string
//定义一个类型方法,实现类似装饰器效果
func (f myfun) myfuncMethod() {
fmt.Println("This is a myfun Method,I can do sth before execting the function")
//在这个方法里面调用原函数的方法
f(1, "string")
fmt.Println("This is a myfun Method,I can do sth after execting the function")
}
//定义一个函数
func demo(i int, s string) string {
fmt.Println("This is the demo function.")
return string(i) + s
}
func main(){
//定义一个f变量,类型为myfun
var f myfun
//由于demo函数的签名同myfun的签名一致,可以将demo强制转换为myfun类型,然后赋值给f
f = myfun(demo)
//调用myfun的类型方法
f.myfuncMethod()
}
代码运行结果如下:
This is a myfun Method,I can do sth before execting the function
This is the demo function.
This is a myfun Method,I can do sth after execting the function
实际应用场景
在某些开发过程中,原有的函数功能代码不能无法进一步修改或改动的情况下,或者需要监控函数的执行一些状态数据,如函数执行时长,我们可以定义一个函数类型,为原有的函数添加类型方法。