Golang 常用数据类型转换

Golang 常用数据类型转换, string, int, map, struct

一、Int

1、string 转 int

1
2
3
4
5
6

var str = "1001"

n, _ := strconv.Atoi(str) // 官方 "strconv" 包

fmt.Printf("type:%T, value:%v\n", n, n) // type:int, value:1001

2、string 转 int64

1
2
3
4
5
6

var str = "1001"

n, _ := strconv.ParseInt(str, 10, 64)

fmt.Printf("type:%T, value:%v\n", n, n) // type:int64, value:1001

3、string 转浮点数

1
2
3
4
5
6

  var str = "3.1415926"

  n, _ := strconv.ParseFloat(str, 10)

  fmt.Printf("type:%T, value:%v\n", n, n) // type:float64, value:3.1415926

二、String

1、int 转 string

1
2
3
4
5
6

var n int = 100

str := strconv.Itoa(n)

fmt.Printf("type:%T, value:%v\n", str, str) // type:string, value:100

2、int64 转 string

1
2
3
4
5
6

var n int64 = 100

str := strconv.FormatInt(n, 10)

fmt.Printf("type:%T, value:%v\n", str, str) // type:string, value:100

3、uint32 转 string

1
2
3
4
5
6

var n uint32 = 10

str := strconv.ParseUint(uint64(n), 10)

fmt.Printf("type:%T, value:%v\n", str, str) // type:string, value:100

三、Struct

1、json 转 struct

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15

type Person struct {
  Name string `json:"name"`
  Age  int    `json:"age"`
}

var jsonStr = []byte(`{"name": "neil", "age": 21}`)
var p = Person{}

err := json.Unmarshal(jsonStr, &p)  // 官方 “json” 包
if err != nil {
  fmt.Println("Unmarshal failed:", err)
  return
}
fmt.Printf("p:%#v\n", p) // p:main.Person{Name:"neil", Age:21}

2、map 转 struct

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
type Person struct {
  Name string `json:"name"`
  Age  int    `json:"age"`
}

var m = map[string]interface{}{
  "name": "king",
  "age":  19,
}

jsonStr, err := json.Marshal(m)
if err != nil {
  fmt.Println("Marshal failed:", err)
  return
}

err = json.Unmarshal(jsonStr, &p)
if err != nil {
  fmt.Println("Unmarshal failed too:", err)
  return
}
fmt.Printf("p:%#v\n", p) // p:main.Person{Name:"king", Age:19}

Map

1、json 转 map

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var jsonStr = []byte(`{"name": "neil", "age": 21}`)

var m = map[string]interface{}{}

err := json.Unmarshal(jsonStr, &m)

if err != nil {

  fmt.Println("Unmarshal failed:", err)

  return
}

fmt.Printf("m:%#v\n", m) // m:map[string]interface {}{"age":21, "name":"neil"}

2、 struct 转 map

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
type Person struct {
  Name string `json:"name"`
  Age  int    `json:"age"`
}

var p = Person{
  Name: "king",
  Age:  17,
}

var jsonStr, _ = json.Marshal(p)

var m = map[string]interface{}{}

_ = json.Unmarshal(jsonStr, &m)

fmt.Printf("m:%#v\n", m) // m:map[string]interface {}{"age":17, "name":"king"}
Licensed under CC BY-NC-SA 4.0
Last updated on Jun 28, 2021 10:24 CST
皖ICP备20014602号
Built with Hugo
Theme Stack designed by Jimmy