refer to:
https://sanyuesha.com/2017/07/22/how-to-understand-go-interface/
概念
跟java的很相似
更类似于ruby 中的struct
type: go 中的所有类型,(int ,string, 复杂类型)都是type
interface: type的一种,用来描述行为(包含多个方法),它的类型在编译时不确定,可以是多种struct
struct: type的一种,用来描述结构,也包含方法, 它的类型在编译时就确定了,是显示的
例子:
package main
import ( "fmt" )
// step1. 定义一个struct, 并且包含2个该struct的专属方法
type Student struct {
name string
}
// 可以认为该方法属于上面的struct
func (student Student)GetName() string{
return student.name
}
// 可以认为该方法属于上面的struct
func (student Student) SetName(name string) {
student.name = name
}
// step2. 定义一个interface, 它包含了2个方法的声明
type Human interface{
GetName() string
SetName(string)
}
// step3. 把interface 作为参数,传给该函数
func testGetNameByInterface(human Human) string{
return human.GetName()
}
func main(){
student := Student {
name: "Jim",
}
// 调用,可以看到,该student, 虽然是一个student struct, 但是也是一个 human interface ,所以可以传入进去。
name := testGetNameByInterface(student)
fmt.Println("=== name:", name) // === name: Jim
}
结论:
go的interface 跟 java的很像,都是一个对象包含某个方法。
声明一个二维interface:
sales := [][]interface{}{}
上面的代码中, [][] 表示二维数组
interface{}{} 中, 可以看成: NULL_ELEMENT{}, NULL_ELEMENT 就是interface{}
理解不了就背下来吧。