大家一起学Golang——接口、多态

大家一起学Golang——接口、多态

接口
方法集
多态

接口

接口是定义一组行为的类型,由用户定义的类型来实现,类型实现了接口全部声明的方法,称这个类型实现了这个接口。
空接口:interface{}
接口实现:

type Person interface{
	GetName() string
}
type Student struct{
	Name string
}
func (p *Student) GetName() string {
	return p.Name
}
func main(){
	var p Person
	s1 := Student{}
	s2 := &Student{}
	p = s1  //Student does not implement Person (GetName method has pointer receiver)
	p = s2
	fmt.Printf("%T",p,p)
}

方法集及调用

上述接口方法中,s1不能赋值给接口变量p,因为这是指针接收者 p *Student 实现的接口,所以需要指向Student类型的指针才能实现对应的接口。
如果是值接收者,可以是类型的值或者指针实现对应的接口。如下:

type Person interface{
	GetName() string
}
type Student struct{
	Name string
}
func (p Student) GetName() string {
	return p.Name
}
func main(){
	var p Person
	s1 := Student{}
	s2 := &Student{}
	p = s1  //编译都通过
	p = s2
	fmt.Printf("%T",p,p)
}

下面是方法集规则,仅对接口方法调用

方法接收者
T (t T)
*T (t T) && (t *T)
T 包含匿名字段 S (t T) && (s S)
T 包含匿名字段 *S (t T) && (s S) && (s *S)
*T 包含匿名字段 *S (t T) && (t *T) && (s S) && (s *S)

多态

了解接口和方法集的内容,借助接口可以实现多态,同一接口方法,不同类型实现展现出不同内容就是多态。还是上面的例子

type Person interface{
	GetName() string
}
type Student struct{
	Name string
	Age int
}
func (p *Student) GetName() string {
	fmt.Println("student name:")
	return p.Name
}
func (p *Student) GetAge() int {
	return p.Age
}
type Teacher struct{
	Name string
}
func (q *Teacher) GetName() string{
	fmt.Println("teacher name:")
	return q.Name
}
func main(){
	var p Person
	t := &Teacher{}
	p = t 
	name := p.GetName()
	fmt.Println(name)

	s := &Student{}
	p = s
	P.GetName()
	p.GetAge()  //p.GetAge undefined (type Person has no field or method GetAge) Person没有GetAge方法,此时接口具有方法定义规范作用,约束行为
}
发布了33 篇原创文章 · 获赞 5 · 访问量 7805

猜你喜欢

转载自blog.csdn.net/c0586/article/details/104217435