Suppose we are trying to process a few interfaces, but not sure does a specific function exists.
A simple way is to declare a small interface, and try to cast into it.
Here is a simple example:
package main
import (
"fmt"
)
func TryExecFunc(in interface{}) {
type iFoo interface {
Foo() string
}
if in != nil {
if foo, ok := in.(iFoo); ok {
fmt.Println("implemented, result: ", foo.Foo())
} else {
fmt.Println("not implemented")
}
} else {
fmt.Println("in is nil")
}
}
type MyFoo struct {
Key string
}
func (f *MyFoo) Foo() string {
return fmt.Sprintf("MyFoo: %v", f.Key)
}
func main() {
TryExecFunc(nil)
TryExecFunc("abc")
f := &MyFoo{"my key"}
TryExecFunc(f)
}
The output would seems as follow:
in is nil not implemented implemented, result: MyFoo: my key