我有一个 golang 接口我
type I interface {
A()
B()
}
Run Code Online (Sandbox Code Playgroud)
该接口是 的一个元素type S struct。现在我想向这个接口添加一个函数 C() ,它将被称为 S 类型的对象。但是这个接口由许多其他类型实现(例如:T)。在编译时,我收到一个错误为T does not implement C().
一种解决方法是在 T 中添加一个 C() 的虚拟实现,它只返回 T 的返回类型的值。
有没有更好的方法来做到这一点?
您可以使用单个结构实现多个接口,如下所示。然后,您将让方法接受不同的接口作为参数。
如果您需要一个使用来自两个接口的方法的单个函数,您可以将指针作为单独的参数传递给您的结构(每个接口一个),但是没有什么可以阻止一个接口满足具有较小范围的多个接口,因此您可以创建第三个封装了处理这些情况的功能的接口(参见 IJ 接口示例)。
package main
import (
"fmt"
)
type I interface {
A()
B()
}
// interface 'J' could be defined in an external package, it doesn't matter
type J interface {
C()
}
// encapsulate I & J interfaces as IJ
type IJ interface {
J
I
}
// S will satisfy interfaces I, J & IJ
type S struct {}
func (s *S) A(){
fmt.Println("A")
}
func (s *S) B(){
fmt.Println("B")
}
func (s *S) C(){
fmt.Println("C")
}
func main() {
s := &S{}
doWithI(s)
doWithJ(s)
fmt.Println("===================================")
doWithIAndJ(s)
}
func doWithI(in I){
in.A()
in.B()
}
func doWithJ(in J){
in.C()
}
func doWithIAndJ(in IJ){
in.A()
in.B()
in.C()
}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/DwH7Sr3zf_Y