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 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100