This is a creation in Article, where the information may have evolved or changed.
The problem bothered me all night, but I finally tried it out.
Problem Scenario:
1. I get the value of a pointer by reflection
v := reflect.ValueOf(ptr).Elem()
This pointer points to a struct, because it is the pointer all I use the Elem () function to get the value pointed to.
2. Since the struct that the PTR pointer points to implements an interface, I use an interface assertion method to invoke the function of the interface.
if _,ok := v.Interface().(XXX);ok{ ...}
XXX is my implementation of the interface, it seems that everything is fine, but the problem comes.
//我用一个接口接收ptr的值var i interface{}i = ptrif _,ok := i.(XXX);ok{ //ok为true ...}
As shown above, I use reflection before the interface assertion is no problem. But v. Interface (). (XXX) is always asserted unsuccessfully.
Solution:
My last guess is not because of V. The value after Elem () is the value of the reflect package, so the interface cannot be asserted after calling the interface () function.
To prove my conjecture. I modified the code
//这里我加了个Addr()函数,目的是为了获取v的指针,再通过指针来断言if _,ok := v.Addr().Interface().(XXX);ok{ ...}
After adding the addr () function, the assertion succeeded.
Summarize:
When asserting on reflection, be sure to assert it with a pointer.