接口介绍
接口是一种比较抽象的类型,它不想struct
一样,里面有我们想要的数据类型,接口里面只有接口方法。我们可以利用接口所提供的方法,但是我们并不知道接口里方法的具体实现。
如果要实现一个接口,必须实现这个接口提供的所有方法
示例代码
使用接口实现多态
package main
import "fmt"
// 声明了person接口,内含一个printfInfo方法
type person interface {
printfInfo()
}
// student 结构
type student struct {
name string
age int
}
// teacher 结构
type teacher struct {
name string
age int
}
// student 类型实现了 printfInfo 方法,所以实现了 person 接口,即接口类型参数可以接收 student 类型
func (s student) printfInfo() {
fmt.Printf("I am student and my name is %s, my age is %d\n", s.name, s.age)
}
// teacher 类型实现了 printfInfo 方法,所以实现了 person 接口,即接口类型参数可以接收 teacher 类型
func (t teacher) printfInfo() {
fmt.Printf("I am teacher and my name is %s, my age is %d\n", t.name, t.age)
}
// 参数是一个 person 接口类型
func showInfo(p person) {
p.printfInfo()
}
func main() {
stu := student{
name: "张三",
age: 12,
}
tea := teacher{
name: "李四",
age: 25,
}
// 会调用 student 的方法
showInfo(stu)
// 会调用 teacher 的方法
showInfo(tea)
}
I am student and my name is 张三, my age is 12
I am teacher and my name is 李四, my age is 25
注意要点
我们的student
类型以值接收者的方式实现了person
接口,我们使用值或是指针都可以正确调用
func (s student) printfInfo() {/*...*/}
func showInfo(p person) {
p.printfInfo()
}
func main() {
/.../
showInfo(stu)
showInfo(&stu)
}
我们的student
类型以指针接收者的方式实现了person
接口,我们使用值不能调用,使用指针可以
func (s *student) printfInfo() {/*...*/}
func showInfo(p person) {
p.printfInfo()
}
func main() {
/.../
showInfo(stu) // 出错
showInfo(&stu)
}
出错信息
cannot use stu (type student) as type person in argument to showInfo:
student does not implement person (printfInfo method has pointer receiver)
不能在 showInfo 的参数中使用 stu(student类型)作为 person 类型:student 没有实现 person (printfInfo 方法有指针接收器)
总结
- 如果是值接收者,实体类型的值和指针都可以实现对应的接口
- 如果是指针接收者,那么只有类型的指针能够实现对应的接口