dongtong7990 2018-03-16 15:26
浏览 129
已采纳

通过反射将接口的值设置为指向struc的类型指针的struct字段

I'm trying to set struct.field = &otherStruct. However, I have to use reflection, and otherStruct is of type interface{}.

The error I'm getting is:

reflect.Set: value of type main.StructB is not assignable to type *main.StructB

struct is known. The (real) type of otherStruct is not known, but it is guaranteed, that the assignment is safe (the struct type is identical).

Code:

type StrucA struct {
    Field *StrucB
}

type StrucB struct {}

func main() {
    a := StrucA{}
    var b interface{} = StrucB{}
    //above is set

    // Target: Set a.Field = &b
    reflect.ValueOf(&a).Elem().FieldByName("Field").Set(reflect.ValueOf(b)) // reflect.Set: value of type main.StrucB is not assignable to type *main.StrucB
}

Playground: https://play.golang.org/p/LR_RgfBzsxa

I have tested a lot of different stuff, but I'm unable to solve it.

  • 写回答

1条回答 默认 最新

  • 普通网友 2018-03-16 15:34
    关注

    You first need to allocate a pointer to the type of b, in order to have somewhere to copy the value. Once you have a pointer value, you can set that to Field in a:

    field := reflect.New(reflect.TypeOf(b))
    field.Elem().Set(reflect.ValueOf(b))
    reflect.ValueOf(&a).Elem().FieldByName("Field").Set(field)
    

    https://play.golang.org/p/6-GNSEq0tw3

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看