如何从嵌入式结构的方法反映包含结构的字段? [英] How to reflect fields of containing struct from a method of the embedded struct?

查看:126
本文介绍了如何从嵌入式结构的方法反映包含结构的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  http://play.golang.org/p/fsPqJ-6aLI 
包裹主

导入(
fmt
反映


类型内部结构{
}

类型Outer结构{
内部
Id int
名称字符串
}

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

如果typ.Kind()!= reflect.Struct {
fmt.Printf(%v类型不能检查属性\\\
,typ.Kind())
返回attrs
}

//循环通过struct的字段并设置地图
for i:= 0;我< typ.NumField();如果!p.Anonymous {
v:= reflect.ValueOf(p.Type)
v = v.Elem()
attrs [p.Name] = v.CanSet()

}
}

返回attrs
}

func main(){
val:= Outer {}
fmt.Println(val.Fields())//打印map [],但是我想要map [Id:true name:true]


解决方案

您正在< Inner 中专门调用一个方法,该方法不知道它的嵌入位置。嵌入不是继承,它是简单的自动委派。



您可能希望查看将它们包装在通用持久性界面中的方向,或者甚至可以处理持久化数据类型的通用函数。 b
$ b




现在,如果你真的想试试这个,你可以通过指针地址访问外部结构,但你需要知道你想访问的外部类型,这意味着你不能通过反射来获取它。

  outer:=(* Outer)(unsafe.Pointer(i))
typ:= reflect.TypeOf(* outer)


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\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]
}

解决方案

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)

这篇关于如何从嵌入式结构的方法反映包含结构的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆