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 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器