This is a creation in Article, where the information may have evolved or changed.
Several usage scenarios for the reflect package:
1. Traverse the struct field name (to avoid hard coding of the code)
2. Call the struct method (auto-map)
3. Get the value of the tag tag for the struct (json/xml conversion)
4.//@todo More usage scenarios
Code:
First, $GOPATH/reflectusage/main.go:
Reflect use scenario Package mainimport ("Errors" "FMT" "Reflect" "Reflectusage/config") func main () {//Create Conf instance conf: = config. conf{} opname: = "Create" Conf. Op = &opname conf. Port = 3308 FMT. Printf ("Conf. Port=%d\n\n ", Conf. Port)//structure information t: = reflect. TypeOf (CONF)//value information V: = reflect. ValueOf (conf) Printstructfield (&t) Callmethod (&v, "Sayop", []interface{}{"Db"})//Panic:reflect:Call of unexported Method//callmethod (&v, "getdbconf", []interface{}{}) Gettag (&t, "Op", "JSON") Gettag (& T, "Op", "xml") Gettag (&t, "Nofield", "JSON")}//Scenario 1: Traverse struct field name func Printstructfield (t *reflect. Type) {fieldnum: = (*t). Numfield () for I: = 0; i < fieldnum; i++ {fmt. Printf ("Conf's field:%s\n", (*t). Field (i). Name)} FMT. Println ("")}//Scenario 2: Call the struct method func Callmethod (v *reflect. Value, method string, params []interface{}) {//String method call, and the property of the instance conf can be found. Op f: = (*v). Methodbyname (method) if F.isvalid ({args: = make ([]reflect. Value, Len (params)) for k, param: = range params {args[k] = reflect. ValueOf (param)}//call RET: = F.call (args) if ret[0]. Kind () = = reflect. String {fmt. Printf ("%s called Result:%s\n", Method, Ret[0]. String ())}} else {fmt. Println ("Can ' t call" + method)} FMT. Println ("")}//Scenario 3: Gets the tag tag of the struct, func gettag (t *reflect. Type, field string, TagName string) {var (tagval string Err Error) Fieldval, OK: = (*t). Fieldbyname (field) If OK {tagval = FieldVal.Tag.Get (tagName)} else {err = errors. New ("No field named:" + field)} FMT. Printf ("Get struct[%s] tag[%s]:%s, error:%v\n", field, TagName, Tagval, err) fmt. Println ("")}//@todo more usage scenarios
Second, $GOPATH/reflectusage/config/config.go:
package configtype Db struct { Port int Host string pw string}type Conf struct { Op *string `json:"jsonop" xml:"xmlOpName"` Charlist *string Length *int Num *int Output *string Input *string hidden *string Db}func (this Conf) SayOp(subname string) string { return *this.Op + subname}func (this Conf) getDbConf() Db { return this.Db}
Third, output:
conf.Port=3308conf's field: Opconf's field: Charlistconf's field: Lengthconf's field: Numconf's field: Outputconf's field: Inputconf's field: hiddenconf's field: DbSayOp Called result: create Dbget struct[Op] tag[json]: jsonop, error:<nil>get struct[Op] tag[xml]: xmlOpName, error:<nil>get struct[nofield] tag[json]: , error:no field named:nofield