'How to check if an interface have a function implementation in Go? [duplicate]
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
}
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Burak Serdar |
