Go Reflection with Interface Embedded in Struct: Detecting the Presence of Real Functions
Consider the following struct:
type A interface { Foo() string } type B struct { A bar string }
While it may seem idiomatic to expect that B must implement interface A, Go's type system allows for the embedding of an anonymous interface without requiring an explicit implementation.
Reflection in Go enables accessing methods of embedded interfaces directly from the containing struct's type. However, this can lead to unexpected errors, especially when the embedded interface has no implementing function at runtime.
To determine whether a real function is present for an interface embedded in a struct using reflection, you can employ the following technique:
This approach effectively checks if the pointer to the function in the anonymous interface value is zero. Here's an example:
func main() { bType := reflect.TypeOf(B{}) bMeth, has := bType.MethodByName("Foo") if has && bMeth != nil { fmt.Printf("HAS IT: %s\n", bMeth.Type.Kind()) // Call the function if it exists res := bMeth.Func.Call([]reflect.Value{reflect.ValueOf(B{})}) val := res[0].Interface() fmt.Println(val) } else { fmt.Println("DOESNT HAS IT") } }
This method allows you to safely detect the presence of a real function for an embedded interface without triggering any errors. It provides a way to determine whether or not the interface is partially implemented and to act accordingly.
The above is the detailed content of How Can I Safely Detect the Presence of Embedded Interface Functions in Go Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!