ZhangZhihui's Blog  

 

type Person struct {
    Id         int    `json:"id"`
    GivenName  string `json:"given_name"`
    FamilyName string `json:"family_name"`
    Email      string `json:"email"`
}

func main() {
    person := Person{
        Id:         1,
        GivenName:  "Sau Sheong",
        FamilyName: "Chang",
        Email:      "sausheong@email.com",
    }

    fmt.Printf("%T\n", person)
    t := reflect.TypeOf(person)
    // Only the struct type has the NumField() method. 
    // If you use it on other types, you'll get panic: reflect: NumField of non-struct type string.
    fmt.Println(t, t.NumField()) 
    fmt.Println(reflect.ValueOf(person).Kind())
    fmt.Println("-----------------------")
    str := "abc"
    fmt.Printf("%T\n", str)
    fmt.Println(reflect.TypeOf(str))
    fmt.Println(reflect.ValueOf(str).Kind())
    fmt.Println("-----------------------")
    s := []int{1, 2, 3}
    fmt.Printf("%T\n", s)
    fmt.Println(reflect.TypeOf(s))
    fmt.Println(reflect.ValueOf(s).Kind())
    fmt.Println("-----------------------")
    d := map[int]string{1: "a", 2: "b"}
    fmt.Printf("%T\n", d)
    fmt.Println(reflect.TypeOf(d))
    fmt.Println(reflect.ValueOf(d).Kind())
}

 

zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
main.Person
main.Person 4
struct
-----------------------
string
string
string
-----------------------
[]int
[]int
slice
-----------------------
map[int]string
map[int]string
map

 

posted on 2024-05-25 09:38  ZhangZhihuiAAA  阅读(6)  评论(0编辑  收藏  举报