Go语言学习

函数也是一种类型

    在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

实际应用场景

    在某些开发过程中,原有的函数功能代码不能无法进一步修改或改动的情况下,或者需要监控函数的执行一些状态数据,如函数执行时长,我们可以定义一个函数类型,为原有的函数添加类型方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值