dqz7636 2018-11-01 22:58
浏览 6
已采纳

如何使用反射设置用户定义类型的值?

I have a type

type SpecialString *string

I have two reflect values, aVal and bVal (just to be clear aVal and bVal are of type reflect.Value) where

aVal.Type() // *SpecialString
bVal.Type() // *string

In regular code I can create c, a pointer to a special string like so:

a := "foo"
b := SpecialString(&a)
c := &b   

How can I achieve the same using reflection?

aval.Set(bVal) // does not work: "reflect.Set: value of type *string is not assignable to type *SpecialString"
  • 写回答

1条回答 默认 最新

  • dongyakui8675 2018-11-01 23:23
    关注

    You need to convert the types and pay attention to what you can and cannot set. Something like:

    type SpecialString string
    var s string = "source regular string"
    var ss SpecialString
    // Get the reflect.Value of the thing &ss pointing at.
    ssv := reflect.ValueOf(&ss).Elem() 
    // You need to convert string to SpecialString explicitly
    ssv.Set(reflect.ValueOf(s).Convert(ssv.Type())) 
    fmt.Printf("ss = %T %+#v
    ", ss, ss)
    

    https://play.golang.org/p/OtFuS5bAaax

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题