1. go语言被传的神,说什么语言级支持并发,也来尝尝鲜,最近在学习,研究go 的http包源码的时候,有一点很疑惑
一个普通函数可被直接转换成一个接口类型,因为平时一直用java开发,对这一点很不解,后来研究了下,原来go存在一种派生类型:函数类型,mark下
2.go函数类型
废话不多说直接贴代码
package main
import "fmt"
//定义接口
type Animal interface {
Speak(s string)
}
//函数类型
type Action func(s string)
func (a Action) Speak(s string){
a(s)
}
type Dog struct {}
type Cat struct {}
func (d Dog) Speak(s string){
fmt.Println("dog speak ",s)
}
func (d Cat) Speak(s string){
fmt.Println("cat speak ",s)
}
func hello(s string){
fmt.Println("hello,",s)
}
func test(animal Animal){
switch animal.(type) {
case Dog:
dog := animal.(Dog)
dog.Speak("wangwang")
case Cat:
cat := animal.(Cat)
cat.Speak("miaomiao")
default:
animal.Speak("human")
fmt.Println("未知动物")
}
}
func main() {
dog := Dog{}
test(dog)
cat := Cat{}
test(cat)
test(Action(hello))
}
3.打印结果
可看到Action作为函数类型,可把一个普通函数hello转换成一个Animal接口类型,当
animal.Speak执行的时候实际上执行的是hello函数逻辑,前提:
1)Action函数类型实现了Animal接口定义的函数Speak
2)hello函数签名与Action一致
4.总结
根据最近学习发现,go语言很灵活,特别是它的接口机制,不论任何类型,只要完全实现了接口中定义的函数,那么该类型也就实现了某接口,刚一接触确实懵逼,需要慢慢仔细品味