dpi74187 2014-06-20 18:26
浏览 78

golang-对嵌入式结构的反思

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.

  • 写回答

1条回答 默认 最新

  • droxy80248 2014-06-20 18:57
    关注

    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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效