关于golang 混合类型 slice 及 json 转换、遍历示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"encoding/json"
"fmt"
)
type A struct {
Name string
}
type B struct {
City string
}
func main() {
ab := []interface{}{}
a := A{"HUHU"}
ab = append(ab, a)
b := B{"ShangHai"}
ab = append(ab, b)
fmt.Println(ab)
// range
for k, v := range ab {
fmt.Println(k, v)
fmt.Printf("%T\n", v)
switch v.(type) {
case A:
fmt.Println(v.(A).Name)
case B:
fmt.Println(v.(B).City)
}
}
// interface to json byte
buf, err := json.Marshal(ab)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(buf))
// json byte to interface
it := []interface{}{}
json.Unmarshal(buf, &it)
fmt.Println(it)
// range
for k, v := range it {
fmt.Println(k, v)
if rec, ok := v.(map[string]interface{}); ok {
for key, val := range rec {
fmt.Println(key, val)
}
}
}
fmt.Println("Hello, 世界")
}
输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[{HUHU} {ShangHai}]
0 {HUHU}
main.A
HUHU
1 {ShangHai}
main.B
ShangHai
[{"Name":"HUHU"},{"City":"ShangHai"}]
[map[Name:HUHU] map[City:ShangHai]]
0 map[Name:HUHU]
Name HUHU
1 map[City:ShangHai]
City ShangHai
Hello, 世界
本文网址: https://golangnote.com/topic/181.html 转摘请注明来源