GO学习笔记(8)
八. 接口
接口(interface)是一种类型.
8.1. 定义接口
// 定义接口: 接口只有方法声明,没有实现,没有数据字段。 type Mover interface { move() } type dog struct { name string } type pig struct { name string } // 实现接口(实现接口中的方法) func (d dog)move() { fmt.Println("dog:",d.name) } func (p pig)move() { fmt.Println("pig:",p.name) } func interfaceDemo() { var x Mover // 接口类型的变量 var y Mover // 接口类型的变量 var wangcai = dog{name:"wangcai"} x = wangcai // 'Mover' as 'move' method has a pointer receiver x.move() var fugui = &pig{name:"fugui"} y = fugui y.move() }
8.2. 值接收者和引用接收者实现接口的区别
8.3. 面试题: 下面的代码是否能正确编译type People interface {
Speak(string) string } type Stduent struct{} func (stu *Stduent) Speak(think string) (talk string) { if think == "sb" { talk = "你是个大帅比" } else { talk = "您好" } return } func main() { var peo People = Stduent{} // 这里会报错: Cannot use 'Stduent{}' (type Stduent) as type People in assignment Type does not implement 'People' as 'Speak' method has a pointer receiver
// 修改为 var peo People = &Stduent{}
think := "bitch" fmt.Println(peo.Speak(think)) }
8.4. 空接口: 空接口类型的变量可以存储任意类型的变量
8.4.1. 定义
func nilInterface() { // 定义一个空接口x var x interface{} s := "傻X" x = s fmt.Printf("%T %v\n", x, x) // string 傻X a := 100 x = a fmt.Printf("%T %v\n", x, x) // int 100 b := true x = b fmt.Printf("%T %v\n", x, x) // bool true }
8.4.2. 应用
func info(a interface{}) { fmt.Printf("%T %v\n", a, a) } func interfaceUse() { // 空接口作为参数可实现接受任意类型为参数的函数 info(10) // int 10 info(10.2) // float64 10.2 info("傻X") // string 傻X info(false) // bool false // 空接口作为map的值, 实现可保存任意值的map var People = make(map[string]interface{}) People["name"] = "傻X" People["sex"] = 1 People["married"] = true fmt.Println(People) // map[married:true name:傻X sex:1] }