dongxian8272 2014-03-03 17: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 17: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条)

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?