Go 接口应用场景、注意事项和使用细节

接口应用场景




注意事项和使用细节

  • 接口本身不能创建实例,但是可以指向一个实现了该接口的自定义类型的变量(实例)
type Stu struct {
	Name string
}

func (stu Stu) Say() {
	fmt.Println("Stu Say()")
}

type AInterface interface {
	Say()
}
func main() {
	var stu Stu //结构体变量,实现了 Say() 实现了 AInterface
 	var a AInterface = stu
	a.Say()
}
  • 接口中所有的方法都没有方法体,即都是没有实现的方法。
  • 在 Golang 中,一个自定义类型需要将某个接口的所有方法都实现,我们说这个自定义类型实现了该接口。
  • 一个自定义类型只有实现了某个接口,才能将该自定义类型的实例(变量)赋给接口类型
  • 只要是自定义数据类型,就可以实现接口,不仅仅是结构体类型。
type integer int

func (i integer) Say() {
	fmt.Println("integer Say i =" ,i )
}

type AInterface interface {
	Say()
}
func main() {
        var i integer = 10
	var b AInterface = i
	b.Say() // integer Say i = 10
}

 


  • 一个自定义类型可以实现多个接口
type AInterface interface {
	Say()
}

type BInterface interface {
	Hello()
}
type Monster struct {

}
func (m Monster) Hello() {
	fmt.Println("Monster Hello()~~")
}

func (m Monster) Say() {
	fmt.Println("Monster Say()~~")
}

func main() {
	//Monster实现了AInterface 和 BInterface
	var monster Monster
	var a2 AInterface = monster
	var b2 BInterface = monster
	a2.Say()
	b2.Hello()
}
  • Golang 接口中不能有任何变量


  • 一个接口(比如 A 接口)可以继承多个别的接口(比如 B,C 接口),这时如果要实现 A 接口,也必须将 B,C 接口的方法也全部实现
package main
import (
	"fmt"
)

type BInterface interface {
	test01()
}

type CInterface interface {
	test02()
}

type AInterface interface {
	BInterface
	CInterface
	test03()
}

//如果需要实现AInterface,就需要将BInterface CInterface的方法都实现
type Stu struct {
}
func (stu Stu) test01() {

}
func (stu Stu) test02() {
	
}
func (stu Stu) test03() {
	
}

func main() {
	var stu Stu
	var a AInterface = stu
	a.test01()
}

  • interface 类型默认是一个指针(引用类型),如果没有对 interface 初始化就使用,那么会输出 nil
  • 空接口 interface{} 没有任何方法,所以所有类型都实现了空接口, 即我们可以把任何一个变量赋给空接口。
type T  interface{

}

func main() {
	var t T = stu //ok
	fmt.Println(t)
	var t2 interface{}  = stu
	var num1 float64 = 8.8
	t2 = num1
	t = num1
	fmt.Println(t2, t)
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值