对嵌入式结构的反思

对嵌入式结构的反思

本文介绍了golang - 对嵌入式结构的反思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个像这样的结构:

  type B struct {
X string
Y string


type D struct {
B
Z string
}

我想反思D并得到字段X,Y,Z.



直觉上,在尝试解决方案之前,我假设我能够遍历结构D并使用反射(X,Y,Z)获取所有字段,并且不必处理B.



但正如你所看到的,我只能看到使用反射而不是它的字段的嵌入式结构B.





有没有办法让我做B在D上反映时是否完全透明?



为什么我要这个?

对一个常见结构(这里是例子中的B)进行图像处理,通过使用嵌入来在多个其他结构中使用该结构。使用反射,尝试将D复制到另一个包中的另一个类似结构中。复制的目标结构将具有平坦布局的所有属性(不嵌入那里)。所以从源到目的地有一个不匹配(嵌入vs没有嵌入),但所有平坦布局的属性都是相同的。我不想为每个结构创建自定义解决方案。

解决方案

您所期望的'透明度'只是语法糖,与数据表示无关。如果你想有一个使数据结构变得平坦的函数,你必须自己编写它。



例如():

  func DeepFields iface interface {})[] reflect.Value {
fields:= make([] reflect.Value,0)
ifv:= reflect.ValueOf(iface)
ift:= reflect。 TypeOf(iface)

for i:= 0;我< ift.NumField(); i ++ {
v:= ifv.Field(i)

switch v.Kind(){
case reflect.Struct:
fields = append(fields,DeepFields( v.Interface())...)
默认值:
fields = append(fields,v)
}
}

返回字段
}


Given a struct like so:

type B struct {
    X string
    Y string
}

type D struct {
    B
    Z string
}

I want to reflect on D and get to the fields X, Y, Z.

Intuitively, before attempting the solution, I was assuming I would be able to traverse the struct D and get all fields using reflection (X, Y, Z) and won't have to deal with B.

But as you can see, I only see the embedded struct B using reflection and not its fields.

http://play.golang.org/p/qZQD5GdTA8

Is there a way I can make B fully transparent when reflecting on D?

Why do I want this?

Imaging a common struct (B in the example here), that is used in multiple other structs by using embedding. Using reflection, the attempt is to copy D into another similar struct in a different package. The destination struct for copying will have all attributes flatly laid out (no embedding there). So there is a mismatch from the source to the destination (embedding vs no embedding) but all the attributes flatly laid out are the same. I don't want to create custom solutions for each struct.

解决方案

The 'transparency' you expected is just syntactic sugar and has nothing to do with the data representation. If you want to have a function that flattens your data structure, you would have to write it by yourself.

For example (On play):

func DeepFields(iface interface{}) []reflect.Value {
    fields := make([]reflect.Value, 0)
    ifv := reflect.ValueOf(iface)
    ift := reflect.TypeOf(iface)

    for i := 0; i < ift.NumField(); i++ {
        v := ifv.Field(i)

        switch v.Kind() {
        case reflect.Struct:
            fields = append(fields, DeepFields(v.Interface())...)
        default:
            fields = append(fields, v)
        }
    }

    return fields
}

这篇关于golang - 对嵌入式结构的反思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 22:39