• notice
  • Congratulations on the launch of the Sought Tech site

Interface assertion problem after go reflection

This problem bothered me all night, but I finally tried it out.

Problem scenario:

1. I get the value of a pointer through reflection

v := reflect.ValueOf(ptr).Elem()

This pointer points to a structure, because it is a pointer so I used the Elem() function to get the value pointed to.

2. Because the structure pointed to by the ptr pointer implements an interface, I use the interface assertion method to call the function of the interface.

if _,ok := v.Interface().(XXX);ok{
   ...}

 XXX is the interface I implemented, and it looks like everything is fine, but here comes the problem.

//I use an interface to receive the value of ptr
var i interface{}
i = ptr
if _,ok := i.(XXX);ok{
    //ok is true
    ...
}

As shown above, before I used reflection, the interface assertion was fine. But v.Interface().(XXX) always asserts unsuccessful.

solution:

I finally guessed whether it was because the value after v.Elem() was the Value structure value of the reflect package, so the interface could not be asserted after calling the Interface() function.

To prove my conjecture. I modified the code

//Here I added an Addr() function, the purpose is to get the pointer of v, and then assert through the pointer
if _,ok := v.Addr().Interface().(XXX);ok{
    ...
}

After adding the Addr() function, the assertion was successful.

Summarize:

When making assertions during reflection, be sure to use pointers to assert.


Tags

Technical otaku

Sought technology together

Related Topic

1 Comments

author

atorvastatin 40mg us & lt;a href="https://lipiws.top/"& gt;buy atorvastatin cheap& lt;/a& gt; buy generic atorvastatin over the counter

Eqswes

2024-03-07

Leave a Reply

+