Interface assertion problem after go reflection

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.