教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Go 接口应用场景、注意事项和使用细节

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

发布时间:2021-04-28   编辑:jiaochengji.com
教程集为您提供Go 接口应用场景、注意事项和使用细节等资源,欢迎您收藏本站,我们将为您提供最新的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)
}

 

到此这篇关于“Go 接口应用场景、注意事项和使用细节”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
Go 接口应用场景、注意事项和使用细节
photoshop合成跌落海底的海底场景制作教程
C/C /Go混合编程实践之GoJieba
还在担心服务挂掉?Sentinel Go 让服务稳如磐石
Go 开发关键技术指南 | 为什么你要选择 Go?(内含超全知识大图)
GO接口应用场景说明
基于类型系统的面向对象编程语言Go
19小接口的妙用
Go 语言到底适合干什么?
go 函数末尾缺少返回值_王垠:Go语言野心勃勃,实际情况又如何

[关闭]
~ ~