這個程序的輸出爲地圖[],但我想圖。[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]
}
我很努力,我知道我應該繼續前進,但似乎你應該能夠在運行時反映委託堆棧。 – Krut
是的,信息只是不存在。如果你做了一個堆棧跟蹤,你可以看到在val的地址上'Fields'被稱爲'(* Inner).Fields'。所以函數知道結構的地址,並且它至少是一個Inner,但看不到原始類型。 – JimB