dtxpz8785 2019-06-14 07:54
浏览 79
已采纳

如何在reflect.Call返回中访问自定义类型?

I know its not idiomatic to write generic functions in Go, but I want to explore my options before I dive into the go generate.

The problem I have is that the Value.Call() returns a slice where the element I interested in is a pointer to a custom struct. Seems like I cant find a way to access this.

returns := listMethod.Call([]reflect.Value{reflect.ValueOf(filter)})
fmt.Println(returns)

output

[<vspk.EnterpriseProfilesList Value> <*bambou.Error Value>]

type definition:

type EnterpriseProfilesList []*EnterpriseProfile

I want to get access to the vspk.EnterpriseProfilesList, but I am struggling to make it.

If I try to retrieve the underlying value like this:

returns := listMethod.Call([]reflect.Value{reflect.ValueOf(filter)})
ret1 := returns[0].Interface()
fmt.Println(ret1)

I receive

[0xc0000fc7e0]
  • 写回答

1条回答 默认 最新

  • duanbu1421 2019-06-14 07:57
    关注

    Value.Call() returns a value of type []reflect.Value. What you're interested in is the first value of that slice: returns[0].

    This will be of course of type reflect.Value. To extract the value wrapped in it, use Value.Interface().

    This will be of type interface{}. If you need the concrete type, use a type assertion:

    returns[0].Interface().(spk.EnterpriseProfilesList)
    

    For example:

    if list, ok := returns[0].Interface().(spk.EnterpriseProfilesList); ok {
        // here list is of type spk.EnterpriseProfilesList
    } else {
        // it was nil or not of type spk.EnterpriseProfilesList
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低