Compile time check for OR in interface

Hi,

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 two SendEND_AND_CALLBACK using different name.

func (this *MqC) SendEND_AND_CALLBACK (token string, data ServiceI, timeout int64) {
  hdl := this.getHdl()
  token_ptr := (C.MQ_TOK)(C.CString(token))
  defer C.free((unsafe.Pointer)(token_ptr))
  data_ptr := lockerSet(data)
  var errVal C.enum_MqErrorE = C.gomsgque_SendEND_AND_CALLBACK (hdl, token_ptr, data_ptr, (C.MQ_TIME_T)(timeout))
  if (errVal == C.MQ_ERROR) { MqErrorEException((C.MQ_MNG)(hdl), errVal) }
}

a possible solution would be an OR interface

type Service1I interface...
type Service2I interface...

type ServiceI interface ?OR? {
  Service1I
  Service2I
}
1 Like

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)
}

https://play.golang.org/p/71BNYxDZtev

2 Likes

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.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.