Golang 接口

接口介绍

接口是一种比较抽象的类型,它不想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 方法有指针接收器)

总结

  • 如果是值接收者,实体类型的值和指针都可以实现对应的接口
  • 如果是指针接收者,那么只有类型的指针能够实现对应的接口
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值