简单了解下 Interface

基本概念

来自于官方文档的说明: An interface type defines a type set . A variable of interface type can store a value of any type that is in the type set of the interface. Such a type is said to implement the interface

翻译:一个接口类型定义一个类型集合。接口类型的变量可以存储接口类型集合中任何类型的值。这样的类型被认为是实现了接口

重点是后面这段话,我们来进行分段解释。

  • 接口类型的变量可以存储接口类型集合中任何类型的值

    这意味着如果你有一个接口,该接口定义了一些方法,那么任何具有这些方法的类型的值都可以被存储在该接口类型的变量中

  • 这样的类型被认为是实现了接口

    在Go中,类型不需要显示声明它实现了某个接口。只要类型具有接口所需的所有方法,它就被视为实现了接口。

案例: 假设我们有以下的接口定义:

go 复制代码
type Duck interface {
    shout() string
}

现在,我们定义了两个类型,它们都有 shout 方法:

go 复制代码
type Dog struct {
    name string
}

func (dg Dog) shout() string {
    return dg.name + " is shouting"
}

type Bird struct {
    name string
}

func (bd Bird) shout() string {
    return bd.name + " is shouting"
}

由于DogBird都有shout方法,他们都实现了Duck接口。因此,我们可以这样做:

go 复制代码
func main() {
    var duck Duck

    duck = Dog{name: "Dog"}
    fmt.Println(duck.shout()) // 输出:Dog is shouting

    duck = Bird{name: "Bird"}
    fmt.Println(duck.shout()) // 输出: Bird is shouting
}

在这个例子中,duck 是一个 Duck 接口类型的变量。尽管DogBird是完全不同的类型,但由于它们都实现了Duck接口,所以它们的实例都可以赋值给duck变量,并调用它们的shout方法。

  • 接口不仅可以存储方法,还可以存储类型元素 我们先来看一个函数
go 复制代码
func speak[T float64 | float32 | int | string | rune | byte] () {}

上述案例声明了一个泛型函数speak,泛型T它表示float64 | float32 | int | string | rune | byte这些类型,如果还想为T增加类型,便还需往后面添加,不美观也不便于检查。那么我们就可以使用interface来表示。

go 复制代码
type GeneralType interface {
    float64 | float32 | int | string | rune | byte
}

func speak[T GeneralType] () {}

空接口

上文我们知道,如果一个类型满足接口的所有方法,该类型被认为实现了接口。当一个接口内没有定义任何方法(空接口),那么每个类型都被认为实现了它,使得它可以代表任何值。

go 复制代码
var anything interface{}

anything = 100
fmt.Println(anything) // 输出:100
anything = "3.141592653589793"
fmt.Println(anything) // 输出:3.141592653589793
anything = true
fmt.Println(anything) // 输出:true

嵌入式接口(Embedded interfaces)

经典套娃环节又来了,Go允许我们在接口内部除了写类型元素和方法,还可以写接口。表示合并了接口内部的所有方法

go 复制代码
type Dog interface {
    walk()
}

type Bird interface {
    shout()
}

type Animal interface {
    Dog()
    Bird()
}

Animal接口嵌套了 DogBird接口,相当于合并了Dog接口和Bird接口内部的所有方法。

相关推荐
学习星球6 小时前
# 6G通感一体化(ISAC)技术深度解析——从原理到实战> <br />
go·信息与通信·媒体
小满zs9 小时前
Go语言第十章(指针)
后端·google·go
学习星球1 天前
6G核心网架构深度解析——AI Native时代的网络变革
网络·人工智能·5g·架构·go·信息与通信
ylj_dev2 天前
从 0 构建 AI Workload Platform(九):真实场景、最小控制台与开源发布
go·react·开源项目·工作流·ai agent
tyung2 天前
znet 数据编解码:字节流怎么变成消息
后端·网络协议·go
leeyi2 天前
数据库迁移不翻车:golang-migrate 实战,143 个 DDL 有序执行(第97篇-E83)
go·aigc·agent
用户330144867632 天前
mheap:全局堆管理器
go
用户330144867632 天前
10. Large 对象分配:直接路径
go
yinchnag2 天前
CRTP:奇异递归模板模式在 Go 模块系统中的实现
设计模式·go
ylj_dev3 天前
从 0 构建 AI Workload Platform(七):可观测性、故障注入与性能验证
go·prometheus·可观测性·opentelemetry·故障注入