dtcmadj31951 2015-08-21 16:13
浏览 74
已采纳

go(reflect):如何实例化任意类型并设置一个已知的嵌入字段

Consider the following type declaration:

type (
    Embedded struct{}
    Actual1 struct{ *Embedded }
    Actual2 struct{ *Embedded }
    Actual3 struct{ *Embedded }
)

Now consider the following function, where i may be of type Actual1, Actual2, or Actual3 (or any other type that embeds Embedded in like manner). I can't do a type assertion or a type switch because I can't know how many types contain Embedded, all I know about i is that it does indeed embed the Embedded type. This function will instantiate a new instance of the same type as i and set embed on that newly instantiated copy instance.

func New(i interface{}, field *Embedded) interface{} {
    // Step 1. instantiate new instance of `i`, of same underlying type as `i`
    // Step 2. set `i.Embedded` to `field`
    // Step 3. return the new instance.
}

Here's what usage would look like:

func main() {
    actual := &Actual1{}
    embed := &Embedded{}
    copied := New(actual, embed)
    if copied.(Actual1).Embedded != embed {
        log.Fatal("It didn't work!")
    }
}

A correct implementation of the New(...) function cannot use type assertions or a type switch and would also not result in the call to log.Fatal shown above.

I think what I'm asking for is a combination of these two questions:

  • 写回答

1条回答 默认 最新

  • drgweamoi473182981 2015-08-21 16:23
    关注

    Using reflection, you can do it like that:

    • get the type of the struct from the type of the pointer to it
    • instantiate and deref it
    • set the value of the field (looking it up by name) with the value of your pointer

    Code:

    v := reflect.New(reflect.TypeOf(i).Elem()).Elem()
    f := reflect.ValueOf(field)
    v.FieldByName("Embedded").Set(f)
    return v.Interface()
    

    Playground: http://play.golang.org/p/fX413svXDv

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大