douanrang4728 2018-05-18 09:27
浏览 24

转换反射值以键入golang?

Is it possible to dynamically cast a value generated by reflect.Zero/New back to an arbitrary type?

https://blog.golang.org/laws-of-reflection seems to suggest not (as go is statically typed). That pretty much seems to limit the uses of reflection as far as I can see, as you always need to be aware of the type you are working with.

Here's an example of what I mean:

package main

import (
    "fmt"
    "reflect"
)

type A struct {
    Name string
}

func main() {

    a := &A{Name: "Dave"}
    fmt.Println(a)

    //create a nil pointer of an arbitrary type
    dynamicType := reflect.TypeOf(a)
    dynamicNil := reflect.Zero(dynamicType).Interface()
    a = dynamicNil //is it possible to do this without explicitly casting to A (ie. avoiding `a = dynamicNil.(*A)`)
    fmt.Println(a)
}
  • 写回答

1条回答 默认 最新

  • du5114 2018-05-18 09:38
    关注

    Your question's prose and code contradict.

    In your code, dynamicNil has the type interface{}, not reflect.Value as the prose suggests. As a has concrete type *A you'll have to type-assert dynamicNil to *A. There's no way around that.

    Also note that Go doesn't have casts -- only type-conversions and assertions.

    Edit: maybe you're looking for reflect.Value.Set? it's unclear to me.

    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算