go任意类型转字符串
直接上代码
package main import ( "encoding/json" "fmt" "strconv" ) type Result struct { RequestID string `json:"request_id"` Code string `json:"code"` Msg string `json:"msg"` } func main() { var a Result a.RequestID = `123456789` a.Code = `999` a.Msg = `success` b := Strval(a) fmt.Println(b) } // Strval 获取变量的字符串值 // 浮点型 3.0将会转换成字符串3, "3" // 非数值或字符类型的变量将会被转换成JSON格式字符串 func Strval(value interface{}) string { var key string if value == nil { return key } switch value := value.(type) { case float64: key = strconv.FormatFloat(value, 'f', -1, 64) case float32: key = strconv.FormatFloat(float64(value), 'f', -1, 64) case int: key = strconv.Itoa(value) case uint: key = strconv.Itoa(int(value)) case int8: key = strconv.Itoa(int(value)) case uint8: key = strconv.Itoa(int(value)) case int16: key = strconv.Itoa(int(value)) case uint16: key = strconv.Itoa(int(value)) case int32: key = strconv.Itoa(int(value)) case uint32: key = strconv.Itoa(int(value)) case int64: key = strconv.FormatInt(value, 10) case uint64: key = strconv.FormatUint(value, 10) case string: key = value case []byte: key = string(value) default: newValue, _ := json.Marshal(value) key = string(newValue) } return key }