函数也是一种类型
2018-11-12 本文已影响0人
bocsoft
adding_func_to_func.go
package attaching_func_to_a_func
import "fmt"
//在Go中,func(函数)也是一种类型,你可以给它指定一个类型名称、增加方法
type IO func(input string)string
//给函数增加方法
func (io IO) Print(input string){
o := io(input)
fmt.Println("IN: ",input)
fmt.Println("OUT: ",o)
}
adding_func_to_func_test.go
package attaching_func_to_a_func
import (
"fmt"
"reflect"
"strings"
"testing"
)
func TestFuncRun(t *testing.T){
m := IO(func(i string) string {//函数执行逻辑
r := strings.Replace(i, "lower", "upper", 1)
return strings.ToUpper(r)
})
fmt.Println("type:",reflect.TypeOf(m))//type: attaching_func_to_a_func.IO
m.Print("hi,this is lower case")
/*
输出结果:
IN: hi,this is lower case
OUT: HI,THIS IS UPPER CASE
*/
t.Logf("Pass!")
}