Home > Article > Backend Development > How Can I Determine Method Existence in Go?
Querying Method Existence in Go
In Go, unlike Objective-C, there is no explicit mechanism to check if an object has a particular method. However, there are several approaches to address this need.
Simple Method Check
You can define an interface with only the method you're interested in and perform a type assertion against your object:
i, ok := myInstance.(InterfaceImplementingThatOneMethodIcareAbout)
Alternatively:
i, ok = myInstance.(interface{ F() })
A true value for ok indicates that the method exists.
Advanced Approach: Reflect Package
The reflect package provides a more comprehensive way to introspect types:
st := reflect.TypeOf(myInstance) m, ok := st.MethodByName("F")
If ok is false, the method doesn't exist. Otherwise, you can invoke the method using m.F().
The above is the detailed content of How Can I Determine Method Existence in Go?. For more information, please follow other related articles on the PHP Chinese website!