golang中的接口 本人感觉是比较难理解的
总结一下:
1.接口相当于一个类的多态,一个包含了方法的集合,返回的集合,但是没有实现。
2.需要函数体去调用接口中的所有函数体。
3.函数体调用(也可以理解为继承)了接口,就会拥有所有的接口的方法集合,必须全部调用或者实现。
代码一:
package main
import (
"fmt"
)
// 定义一个接口
type People interface {
ReturnName() string
}
// 定义一个结构体
type Student struct {
Name string
}
// 定义结构体的一个方法。
// 突然发现这个方法同接口People的所有方法(就一个),此时可直接认为结构体Student实现了接口People
func (s Student) ReturnName() string {
return s.Name
}
func main() {
cbs := Student{Name:"咖啡色的羊驼"}
var a People
// 因为Students实现了接口所以直接赋值没问题
// 如果没实现会报错:cannot use cbs (type Student) as type People in assignment:Student does not implement People (missing ReturnName method)
a = cbs
name := a.ReturnName()
fmt.Println(name) // 输出"咖啡色的羊驼"
}
代码二:
package main
import (
"fmt"
)
// 定义一个结构体
type Student struct {
Name string
}
// 类型断言
func main() {
Params := make([]interface{}, 3)
Params[0] = 88 // 整型
Params[1] = "咖啡色的羊驼" // 字符串
Params[2] = Student{Name: "cbs"} // 自定义结构体类型
// Comma-ok断言
for index, v := range Params {
if _, ok := v.(int); ok {
fmt.Printf("Params[%d] 是int类型 \n", index)
} else if _, ok := v.(string); ok {
fmt.Printf("Params[%d] 是字符串类型\n", index)
} else if _, ok := v.(Student); ok {
fmt.Printf("Params[%d] 是自定义结构体类型\n", index)
} else {
fmt.Printf("list[%d] 未知类型\n", index)
}
}
// switch判断
for index, v := range Params {
switch value := v.(type) {
case int:
fmt.Printf("Params[%d] 是int类型, 值:%d \n", index,value)
case string:
fmt.Printf("Params[%d] 是字符串类型, 值:%s\n", index,value)
case Student:
fmt.Printf("Params[%d] 是Person类型, 值:%s\n", index,value)
default:
fmt.Printf("list[%d] 未知类型\n", index)
}
}
}