我試圖實現(xiàn)一個函數(shù)來打印帶有反射和 DFS 的結(jié)構(gòu)樹interface{}。但是我發(fā)現(xiàn)很難取消對多級指針的引用(NumField()不能與指針一起使用)。就像:func Tree(i interface{}) { ......}var a = 10var b = &avar c = &bTree(c)在我看來,也許:for reflect.ValueOf(i).Kind() == reflect.Ptr { t := i.(reflect.Typeof(i)) i = *t}可以工作,但事實并非如此。有什么辦法可以解決這個問題嗎?
3 回答

繁花如伊
TA貢獻(xiàn)2012條經(jīng)驗 獲得超12個贊
使用反射你可以這樣做:
rt := reflect.ValueOf(i).Type()
for rt.Kind() == reflect.Ptr {
rt = rt.Elem()
}
// rt is non-pointer type
https://play.golang.com/p/YbT1p4R3_1u

SMILET
TA貢獻(xiàn)1796條經(jīng)驗 獲得超4個贊
你正在尋找reflect.Indirect(interface{}),
// Indirect returns the value that v points to.
// If v is a nil pointer, Indirect returns a zero Value.
// If v is not a pointer, Indirect returns v.
rv := reflect.Indirect(v)
- 3 回答
- 0 關(guān)注
- 146 瀏覽
添加回答
舉報
0/150
提交
取消