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

Kru*_*rut 6 go

该程序的输出是map[],但我想要map[Id:true name:true]

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

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]
}
Run Code Online (Sandbox Code Playgroud)

Jim*_*imB 7

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

您可能希望将它们包装在一个通用的持久化接口中,甚至是一个可以处理持久化数据类型的通用函数中。


现在,如果您确实想尝试此操作,则可以通过指针地址访问外部结构,但您需要知道要访问的外部类型,这意味着您无法通过反射获取它。

outer := (*Outer)(unsafe.Pointer(i))
typ := reflect.TypeOf(*outer)
Run Code Online (Sandbox Code Playgroud)