dongxian8272 2014-03-03 09:27
浏览 23
已采纳

如何从嵌入式结构的方法反映包含结构的字段?

The output of this program is map[], but I want map[Id:true name:true]

I'm trying to dry up some of my SQL CRUD code and thought it would be nice to embed a persistence struct that handles reading and writing to the database. In the example below, the persistence struct would be Inner and my model would be Outer. Thanks!

http://play.golang.org/p/fsPqJ-6aLI
package main

import (
    "fmt"
    "reflect"
)

type Inner struct {
}

type Outer struct {
    Inner
    Id   int
    name string
}

func (i *Inner) Fields() map[string]bool {
    typ := reflect.TypeOf(*i)
    attrs := make(map[string]bool)

    if typ.Kind() != reflect.Struct {
        fmt.Printf("%v type can't have attributes inspected
", typ.Kind())
        return attrs
    }

    // loop through the struct's fields and set the map
    for i := 0; i < typ.NumField(); i++ {
        p := typ.Field(i)
        if !p.Anonymous {
            v := reflect.ValueOf(p.Type)
            v = v.Elem()
            attrs[p.Name] = v.CanSet()

        }
    }

    return attrs
}

func main() {
    val := Outer{}
    fmt.Println(val.Fields()) // prints map[], but I want map[Id:true name:true]
}

展开全部

  • 写回答

2条回答 默认 最新

  • dr5779 2014-03-03 09:51
    关注

    You can't. You're specifically calling a method on Inner, which has no knowledge of where it's embedded. Embedding isn't inheritance, it's simple automatic delegation.

    You probably want to look in the direction of wrapping these in a common persistence interface, or even a generic function that can handle persisting your data types.


    Now, if you really want to try this, you can get access to the outer struct through the pointer address, but you will need to know that outer type you want to access, which means that you can't get it via reflection.

    outer := (*Outer)(unsafe.Pointer(i))
    typ := reflect.TypeOf(*outer)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部