Golang detecting variable types by reflection

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

What's wasting today is tomorrow to those who died yesterday; What's the future of hate now?

What you are wasting today is the tomorrow that the man who died yesterday expects, and what you dislike is now the future you will never go back to.

Simply record it.

Package Mainimport ("reflect" "FMT" "strings") type Foo struct {A int ' tag1: "Tag1" Tag2: "Second Tag" ' B string}func Main () {f: = Foo{a:10, B: "Salutations"}fptr: = &fm: = map[string]int{"A": 1, "B": 2}ch: = make (chan int) sl:= []int{1,32,34}str : = "string var" strPtr: = &strtmap: = Examiner (reflect. TypeOf (f), 0) Tmapptr: = Examiner (reflect. TypeOf (Fptr), 0) TMAPM: = Examiner (reflect. TypeOf (M), 0) TMAPCH: = Examiner (reflect. TYPEOF (CH), 0) TMAPSL: = Examiner (reflect. TYPEOF (SL), 0) Tmapstr: = Examiner (reflect. TypeOf (str), 0) Tmapstrptr: = Examiner (reflect. TypeOf (STRPTR), 0) fmt. Println ("TMap:", TMap) fmt. Println ("Tmapptr:", Tmapptr) fmt. Println ("TMAPM:", TMAPM) fmt. Println ("tmapch:", tmapch) fmt. Println ("TMAPSL:", TMAPSL) fmt. Println ("Tmapstr:", Tmapstr) fmt. Println ("Tmapstrptr:", TMAPSTRPTR)}func Examiner (t reflect. Type, Depth int) Map[int]map[string]string{outtype: = Make (map[int]map[string]string) Outtype = Map[int] map[string] string{depth:{"Name": T.name (), "Kind": T.kind (). String ()}}//If the need for a secondaryContinue to detect the type of element switch T.kind () {case reflect. Array, reflect. Chan, reflect. Map, reflect. PTR, reflect.  Slice:outtype = Make (map[int]map[string]string) TMAP: = Examiner (T.elem (), depth) for k, V: = range tmap{outtype[k] = v}case Reflect. Struct:outtype = Make (map[int]map[string]string) for I: = 0; I < T.numfield (); i++ {f: = T.field (i) outtype[i] = map[string]string{"Name": F.name, "Kind": f.type.string (),}}}return Outtype}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.