I have a go function which accept as second parameter an interface ServiceI. My problem is that
I would like to accept two interfaces ServiceI OR Service2I. I know I can use type interface{} and check the type on run-time but I want to have a compile-time check. The function lockerSet(data), which create the handle, has no problem with different interfaces.
AS go has no overload, an compile-rime-check would require twoSendEND_AND_CALLBACK using different name.
Embedding interfaces is fine, the other option would be defining one more interface for your function. I would go for it. Let’s say if you add new Interfacer1 behaviour, you will get compile them error that says your file doesn’t implement the new behaviour. On the other hand if you define new interface for your function, you know exactly what behaviours you expect from the concrete object.
import "fmt"
type File struct {
data string
}
func (f *File) Read() string {
return f.data
}
func (f *File) Write(d string) {
f.data = d
}
type Interfacer1 interface {
Read() string
// try to add ReadByte() and see what happens
}
type Interfacer2 interface {
Write(d string)
}
type InterfacerEmbed interface {
Interfacer1
Interfacer2
}
type InterfacerGen interface {
Read() string
Write(d string)
}
func io(file InterfacerEmbed) {
file.Write("writed data")
fmt.Println(file.Read())
}
func io2(file InterfacerGen) {
file.Write("io2 writed data")
fmt.Println(file.Read())
}
func main() {
reader := &File{}
io(reader)
io2(reader)
}
Go doesn’t have unions or sum types like you would need here. If there is some commonality between the two interfaces you can declare a new interface to cover just that commonality. Otherwise you are stuck with using either two different functions or interface{} and type assertions.