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)
}
}
}