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

时间:2014-03-03 17:27:44

标签: go

此程序的输出是 map [] ,但我想地图[Id:真实姓名:真]

我试图干掉我的一些SQL CRUD代码,并认为嵌入一个处理读写数据库的持久性结构会很好。在下面的示例中,持久性结构将是Inner,我的模型将是Outer。谢谢!

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\n", 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]
}

1 个答案:

答案 0 :(得分:3)

你做不到。你专门在Inner上调用一个方法,它不知道它嵌入的位置。嵌入不是继承,它是简单的自动委托。

您可能希望在公共持久性接口中查看这些内容,或者甚至是可以处理持久化数据类型的通用函数。


现在,如果确实想要尝试这个,你可以通过指针地址访问外部结构,但是你需要知道你想要访问的外部类型,这意味着你无法通过反思得到它。

outer := (*Outer)(unsafe.Pointer(i))
typ := reflect.TypeOf(*outer)
相关问题