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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么