-3

I have a constructor that returns an interface. There are cases when that interface does not have actual implementation of some of its functions. Trying to call these unemplemented functions causes panic. I want to know is there a way to check is it safe to call a function or not, before actually calling it.

Here is the setup.

package main

type i interface {
    Foo()
    Bar()
}

type s struct {
    i
}

func (r s) Foo() {}

func main() {
    var ii i = &s{}
    ii.Foo() // OK
    ii.Bar() // will panic
}

user3805530
  • 178
  • 1
  • 9
  • 3
    An interface is a _method set_, you cannot use a function, and you cannot have an unimplemented method. – JimB Apr 22 '22 at 16:30
  • @JimB despite the fact I can. Here is the safe implementation of that check I was looking for: https://go.dev/play/p/u2aojdYAz4- – user3805530 Apr 23 '22 at 07:58

1 Answers1

0

The type s embeds an interface variable. Any call to interface methods not explicitly declared by s will panic because the embedded interface is nil. You should set that before calling the methods:

var ii i=&s{}
ii.i=<implementation of i>

So, it is not that the type s unimplemented methods. The type s delegates its method implementations to i, which is nil.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59