本篇是對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類型,通常用于范型,避免文章太長,另起一片