标签:ring hello lse sprint ++ case else val amp
package main import ( "reflect" "fmt" ) type User struct { Name string `json:"name"` Age int Sex string } func TestType(a interface{}) { typeOf := reflect.TypeOf(a) fmt.Printf("typeof = %v\n", typeOf) kind := typeOf.Kind() switch kind { case reflect.Int: fmt.Println("a is an int") case reflect.String: fmt.Println("a is a string") } } func TestValue(a interface{}) { valueOf := reflect.ValueOf(a) switch valueOf.Kind() { case reflect.Ptr: i := valueOf.Elem().Type() switch i.Kind() { case reflect.Int: valueOf.Elem().SetInt(10000) case reflect.String: valueOf.Elem().SetString("hello world") } } } func Marshal(a interface{}) { valueOf := reflect.ValueOf(a) typeOf := valueOf.Type() jsonStr := "" switch typeOf.Kind() { case reflect.Struct: numField := typeOf.NumField() for i:=0; i<numField; i++ { structField := typeOf.Field(i) valueField := valueOf.Field(i) name := structField.Name if structField.Tag.Get("json") != "" { name = structField.Tag.Get("json") } if valueField.Type().Kind() == reflect.String { jsonStr += fmt.Sprintf(" \"%s\": \"%v\"", name, valueField.Interface()) } else { jsonStr += fmt.Sprintf(" \"%s\": %v", name, valueField.Interface()) } if numField - i > 1 { jsonStr += ",\n" } } jsonStr = "{\n" + jsonStr + "\n}" } fmt.Printf("%s", jsonStr) } func main() { var a int TestType(a) var b string TestType(b) TestValue(&a) TestValue(&b) fmt.Println(a, b) var user User user.Name = "alex" user.Age = 100 user.Sex = "man" Marshal(user) }
标签:ring hello lse sprint ++ case else val amp
原文地址:https://www.cnblogs.com/vincenshen/p/9534794.html