本篇是对golang 中的interface做一些浅层的、实用的总结
多态
常用场景
interface内仅包含函数类型,然后定义结构体去实现,如下
package mainimport "fmt"type Animal interface {Sound()Act()
}type Cat struct{}func (c *Cat) Sound() {fmt.Println("喵喵喵")
}func (c *Cat) Act() {fmt.Println("抓")
}type Dog struct{}func (d *Dog) Sound() {fmt.Println("汪汪汪")
}func (c *Dog) Act() {fmt.Println("咬")
}func AnimalAct(a Animal) {a.Act()
}func main() {d := &Dog{}AnimalAct(d)
}
嵌入接口
就是接口内包含了接口,套娃
package mainimport "fmt"type Reader interface {Read() string
}type Writer interface {Write(string)
}type ReadWriter interface {Reader // 嵌入Reader接口Writer // 嵌入Writer接口
}type File struct{} // 示例结构体func (f File) Read() string { return "Reading content" }
func (f File) Write(content string) { fmt.Println("Writing:", content) }func main() {var rw ReadWriter = File{} // File实现了ReadWriter接口,因为它实现了ReadWriter中嵌入的所有接口方法fmt.Println(rw.Read()) // 使用Read方法rw.Write("Hello") // 使用Write方法
}
装饰器模式
模拟一个简单场景,需要在原有业务基础上,增加日志
package mainimport "fmt"type Business interface {HandingBusiness()
}type BusinessObj struct {
}func (sr BusinessObj) HandingBusiness() {fmt.Println("处理业务")
}type DecoratedHB struct {Business
}func (dr DecoratedHB) HandingBusiness() {dr.Business.HandingBusiness()fmt.Println("业务完成,记录日志")
}func main() {bo := BusinessObj{}dhb := DecoratedHB{Business: bo}dhb.HandingBusiness()
}
限定类型
嵌套接口
在上文已经举了例子,可以做接口嵌套,如上文,实现ReadWriter必须要同时实现Reader和Writer
限定实现接口的类型
type TestS struct {age int
}func (t TestS) TestS1() {fmt.Println(1111111)
}func (t TestS) speak() {fmt.Println(22222)
}type TestI interface {speak()TestS
}func TestIFunc[TestIType TestI](t TestIType) {fmt.Println(33333333)
}
这里就限制了实现TestI,必须是TestS的实体,而且还要实现speak方法
这里再做一下扩展
type MyNum interface {int | float
}
这样就是限定MyNum只能是int或float类型,通常用于范型,避免文章太长,另起一片