Go では、オブジェクトがメソッドに応答するかどうかをどのように確認しますか?
たとえば、Objective-C では、次のようにして実現できます。
if ([obj respondsToSelector:@selector(methodName:)]) { // if method exists
[obj methodName:42]; // call the method
}
Go では、オブジェクトがメソッドに応答するかどうかをどのように確認しますか?
たとえば、Objective-C では、次のようにして実現できます。
if ([obj respondsToSelector:@selector(methodName:)]) { // if method exists
[obj methodName:42]; // call the method
}
インターフェイスブレース{write_function_declaration_here}内の@evanmcdonnalのソリューションに加えて、関数宣言を記述します
if correctobj, ok := obj.(interface{methodName(func_arguments_here)(return_elements_here)}); ok {
x,... := correctobj.methodName()
}
すなわち
package main
import "fmt"
type test struct {
fname string
}
func (t *test) setName(name string) bool {
t.fname = name
return true
}
func run(arg interface{}) {
if obj, ok := arg.(interface{ setName(string) bool });
ok {
res := obj.setName("Shikhar")
fmt.Println(res)
fmt.Println(obj)
}
}
func main() {
x := &test{
fname: "Sticker",
}
fmt.Println(x)
run(x)
}