登录
首页 >  Golang >  Go问答

使用反射将一个接口{}类型转换为另一个接口{}类型切片

来源:stackoverflow

时间:2024-03-04 23:00:31 469浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《使用反射将一个接口{}类型转换为另一个接口{}类型切片》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我有一个 people 类型的切片,我需要将此切片传递给获取类型“interface {}”的函数。 people 类型“实现”了一个名为 hascustomfield 的接口,但我无法像我正在做的那样在函数内进行类型转换:

type HasCustomField interface {
    GetCustomField() map[string]interface{}
}

type People struct {    
    Name string
    customField map[string]interface{}
}

func (c *People) GetCustomField() map[string]interface{} {
    if c.customField == nil {
        c.customField = make(map[string]interface{})
    }
    return c.customField
}

func main() {
    users := []People{{Name:"Teste"},{Name:"Mizael"}}
    ProcessCustomField(&users)
}

func ProcessCustomField(list interface{}) {
    if list != nil {
        listVal := reflect.ValueOf(list).Elem()

        if listVal.Kind() == reflect.Slice {

             for i:=0; i

结果总是“not ok”,我无法进行转换,我也尝试了其他几种方法,包括通过反射调用方法getcustomfield(),但没有成功。


解决方案


getcustomfield 方法位于指针接收者 *people 上,但切片包含 people 值。获取切片元素的地址以使用指针接收器:

valuereflect := listval.index(i).addr().interface()  // <-- addr()

Run it on the playground

额外的简化:使用切片参数而不是指向切片的指针。

ProcessCustomField(users) // <-- do not take addr here
...

listVal := reflect.ValueOf(list) <-- do not call Elem() here

Run it on the playground

好了,本文到此结束,带大家了解了《使用反射将一个接口{}类型转换为另一个接口{}类型切片》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>