Go语言各种数据类型格式转换
package main import ( "encoding/json" "fmt" "reflect" "strconv" ) type User struct { Id int `json:"id"` Name string `json:"name"` } func main() { //string到int n10, _ := strconv.Atoi("12") fmt.Println(reflect.TypeOf(n10)) // string到int64 n64, _ := strconv.ParseInt("12", 10, 64) fmt.Println(reflect.TypeOf(n64)) // string to float32、float64 f_32, _ := strconv.ParseFloat("3.1415", 32) f_64, _ := strconv.ParseFloat("3.1415", 64) fmt.Printf("%T\n", f_32) // float64 fmt.Printf("%T\n", f_64) // int到string s1 := strconv.Itoa(11) fmt.Println(reflect.TypeOf(s1)) // int64到string s2 := strconv.FormatInt(11,10) fmt.Println(reflect.TypeOf(s2)) // float32/64 to string s3 := strconv.FormatFloat(3.1415, 'E', -1, 32) s4 := strconv.FormatFloat(3.1415, 'E', -1, 64) fmt.Println(reflect.TypeOf(s3)) fmt.Println(reflect.TypeOf(s4)) // int和int64 n_10_64 := int64(11) fmt.Println(reflect.TypeOf(n_10_64)) // int64 to int n_64_10 := int(n_10_64) fmt.Println(reflect.TypeOf(n_64_10)) s := `{"id": 1, "name": "wxnacy"}` // 将字符串反解析为结构体 var user User _ = json.Unmarshal([]byte(s), &user) fmt.Println(user) // {1 wxnacy} // 将字符串反解析为字典 var d map[string]interface{} _ = json.Unmarshal([]byte(s), &d) fmt.Println(d) // map[id:1 name:wxnacy] // 将字符串反解析为数组 s = `[1, 2, 3, 4]` var a []int _ = json.Unmarshal([]byte(s), &a) fmt.Println(a) // [1 2 3 4] // 将结构体解析为字符串 str_user, _ := json.Marshal(user) fmt.Println(string(str_user))// {"id":1,"name":"wxnacy"} // 数组解析为字符串 str_a, _ := json.Marshal(a) fmt.Println(string(str_a)) // [1,2,3,4] <nil> // map解析为字符串 str_d, _ := json.Marshal(d) fmt.Println(string(str_d)) // {"id":1,"name":"wxnacy"} <nil> }