golang 通過reflect 獲取struct信息

本示例主要通過反射,瞭解struct或變量的相關信息,方便調試代碼等。

示例:

  package main
        
        import (
        	"fmt"
        	"reflect"
        )
        
        type Users struct {
        	Id     int
        	Name   string
        	Age    int
        	Market map[int]string
        	Source *Sfrom
        	Ext    Info
        }
        type Info struct {
        	Detail string
        }
        type Sfrom struct {
        	Area string
        }
        
        func (u Users) Login() {
        	fmt.Println("login")
        }
        
        func main() {
        	m := map[int]string{1: "abc"}
        	s := &Sfrom{Area: "beijing"}
        	i := Info{Detail: "detail"}
        	u := &Users{Id: 12, Market: m, Ext: i, Source: s}
        	v := reflect.ValueOf(u)
            Explicit(v, 0)
        }
        
   func Explicit(v reflect.Value, depth int) {
	if v.CanInterface() {
		t := v.Type()
		switch v.Kind() {
		case reflect.Ptr:
			Explicit(v.Elem(), depth)
		case reflect.Struct:
			fmt.Printf(strings.Repeat("\t", depth)+"%v %v {\n", t.Name(), t.Kind())
			for i := 0; i < v.NumField(); i++ {
				f := v.Field(i)
				if f.Kind() == reflect.Struct || f.Kind() == reflect.Ptr {
				fmt.Printf(strings.Repeat("\t", depth+1)+"%s %s : \n", t.Field(i).Name, f.Type())
					Explicit(f, depth+2)
				} else {
					if f.CanInterface() {
						fmt.Printf(strings.Repeat("\t", depth+1)+"%s %s : %v \n", t.Field(i).Name, f.Type(), f.Interface())
					} else {

						fmt.Printf(strings.Repeat("\t", depth+1)+"%s %s : %v \n", t.Field(i).Name, f.Type(), f)
					}
				}
			}
			fmt.Println(strings.Repeat("\t", depth) + "}")
		}
	} else {
		fmt.Printf(strings.Repeat("\t", depth)+"%+v\n", v)
	}
}   

結果:
Users struct {
Id int : 12
Name string :
Age int : 0
Market map[int]string : map[1:abc]
Sfrom struct {
Area string : beijing
}
Info struct {
Detail string : detail
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章