1 int与string
备注:string不可直接转int32,先转为int,再转成int32
package main
import (
"fmt"
"strconv"
)
func main() {
//int 转 string
var a int = 3
str := strconv.Itoa(a)
fmt.Printf("str:类型:%T 值:%s\n", str, str)
var aa string = "2"
aaa, _ := strconv.Atoi(aa)
fmt.Printf("aaa:类型:%T 值:%d\n", aaa, aaa)
//int32 转 string
var b int32 = 3
str32 := fmt.Sprint(b)
fmt.Printf("str32:类型:%T 值:%s\n", str32, str32)
var bb string = "2"
bbb, _ := strconv.Atoi(bb)
bbbb := int32(bbb)
fmt.Printf("bbbb:类型:%T 值:%d\n", bbbb, bbbb)
//int64转string
var c int64 = 3
str64 := strconv.FormatInt(c, 10) //10进制
fmt.Printf("str64:类型:%T 值:%s\n", str64, str64)
var cc string = "2"
ccc, _ := strconv.ParseInt(cc, 10, 64)
fmt.Printf("ccc:类型:%T 值:%d\n", ccc, ccc)
}
2 float与string
备注:string不可直接转float32,先转成float64,再转成float32
package main
import (
"fmt"
"strconv"
)
func main() {
//float32转string
var d float32 = 0.998
flo32 := fmt.Sprintf("%f", d)
fmt.Printf("flo32:类型:%T 值:%s\n", flo32, flo32)
var dd string = "0.998"
ddd, _ := strconv.ParseFloat(dd, 32)
dddd := float32(ddd)
fmt.Printf("dddd:类型:%T 值:%f\n", dddd, dddd)
//float64转string
var e float64 = 0.998
flo64 := strconv.FormatFloat(e, 'f', -1, 32)
fmt.Printf("flo64:类型:%T 值:%s\n", flo64, flo64)
var ee string = "0.998"
eee, _ := strconv.ParseFloat(ee, 64)
fmt.Printf("ddd:类型:%T 值:%f\n", eee, eee)
}
3 结构体与JSON序列化
package main
import (
"encoding/json"
"fmt"
)
type test struct {
Name string
Age int
}
func main() {
c := &test{
Name: "tom",
Age: 12,
}
//JSON序列化:结构体-->JSON格式的字符串
data, err := json.Marshal(c)
if err != nil {
fmt.Println("json marshal failed")
return
}
fmt.Printf("json:%s\n", data)
//JSON反序列化:JSON格式的字符串-->结构体
str := `{"name":"jer","id":0,"sex":"man"}`
type test2 struct {
Name string
Id int
Sex string
}
c1 := &test2{}
err = json.Unmarshal([]byte(str), c1)
if err != nil {
fmt.Println("json unmarshal failed!")
return
}
fmt.Printf("%#v\n", c1)
}
输出:
json:{"Name":"tom","Age":12}
&main.test2{Name:"jer", Id:0, Sex:"man"}
4 map与string
map转string
package main
import (
"encoding/json"
"fmt"
)
func main() {
//创建map
s2 := make(map[string]int)
...
s3, _ := json.Marshal(s2)
str := string(s3)
fmt.Println(str)
}