接口(interface)定义了一个对象的行为规范,只定义规范不实现,由具体的对象来实现规范的细节。
- 了解为什么需要接口以及接口的特点
- 掌握接口的声明和使用 掌握接口值的概念
- 掌握空接口的特点及其使用场景
在Go语言中接口(interface)是一种类型,一种抽象的类型。相较于之前章节中讲到的那些具体类型(字符串、切片、结构体等)更注重“我是谁”,接口类型更注重“我能做什么”的问题。接口类型就像是一种约定——概括了一种类型应该具备哪些方法,在Go语言中提倡使用面向接口的编程方式实现解耦
。
package main
import "fmt"
func main() {
d := Dog{
Name: "狗仔",
}
d.say() //狗仔叫
c := Cat{
Name: "猫咪",
}
c.say() //猫咪叫
doSay(d) //狗仔叫
}
type Dog struct {
Name string
}
func (d Dog) say() {
fmt.Printf("%s叫\n", d.Name)
}
type Cat struct {
Name string
}
func (c Cat) say() {
fmt.Printf("%s叫\n", c.Name)
}
//定义接口 统一调用所有 构造函数的 say
type sayer interface {
say()
}
//对外暴露的 函数
func doSay(arg sayer) {
arg.say()
}
指针传值 上面代码块的例子 是 值传值
package main
import "fmt"
func main() {
var m Move
p := Person{
Name: "lwl",
Age: 18,
}
p1 := &Person{
Name: "zq",
Age: 18,
}
m = p //值类型 无法赋值,所以报错
m = p1 //指针
p.move() //lwl在移动...
p1.move() //zq在移动...
fmt.Println(m)
}
type Person struct {
Name string
Age int8
}
type Move interface {
move()
}
//使用指针接受实现接口,只有类型是指针能够保存到接口变量中
func (p *Person) move() {
fmt.Printf("%s在移动...\n", p.Name)
}
//空接口
类型断定
var emptyinterface interface{}
emptyinterface = true
_, ok := emptyinterface.(int)
fmt.Println(ok)//false
// justifyType 对传入的空接口类型变量x进行类型断言
func justifyType(x interface{}) {
switch v := x.(type) {
case string:
fmt.Printf("x is a string,value is %v\n", v)
case int:
fmt.Printf("x is a int is %v\n", v)
case bool:
fmt.Printf("x is a bool is %v\n", v)
default:
fmt.Println("unsupport type!")
}
}
空接口作为map的值
var studentInfo = make(map[string]interface{})
studentInfo["name"] = "沙河娜扎"
studentInfo["age"] = 18
studentInfo["married"] = false
fmt.Println(studentInfo)