Go Reflection with Interface Embedded in Struct: Identifying "Real" Functions
Consider the following code snippet:
type A interface { Foo() string } type B struct { A bar string }
According to Go's idiomatic approach, the pattern above suggests that B must implement the A interface. However, unlike OOP languages, there's no compile-time check for this. Instead, you can opt to implement only part of the interface.
Reflection lets you retrieve methods of A directly from B's type, even if there's no method with receiver B present. However, this raises a question: how can you detect if a "real" implementation exists before triggering a panic?
To solve this, you can't rely on reflection alone. Instead, consider using a straightforward approach:
method_in_table := B.Foo // Check if the method is nil if method_in_table == nil { fmt.Println("No real implementation found") } else { // Method is present }
Alternatively, you could use the following reflection-based check:
bType := reflect.TypeOf(B{}) bMeth, has := bType.MethodByName("Foo") if !has || bMeth.Func.ptr.IsZero() { // No real implementation found } else { // Method is present }
In this scenario, checking if the ptr field of the bMeth function is zero allows you to determine if the function is in the function table of the anonymous interface value. If it's zero, there's no corresponding method in the B struct, indicating a lack of real implementation.
The above is the detailed content of How Can I Detect a 'Real' Interface Implementation in Go Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!