goland map学习-实践使用练习:判断存在及遍历
对于数据:
type Person struct {
Address string
Age int
Job string
Name string
}
type People map[string]Person
var per = People{
"1": Person{
Address: "1",
Age: 1,
Job: "1",
Name: "1",
},
"2": Person{
Address: "2",
Age: 2,
Job: "2",
Name: "2",
},
}
对于map-struct式的数据来做一些测试实验:
1,判断map的key是否存在,直接使用如下代码段来检查:
if _, exist :=,map_obj[key]; exist {
...
}
2,map数据遍历通常使用for range来遍历其中每个key-val
for key, val := range map_obj{
...
}
或者只取key值:
for key := range map_obj {
fmt.Println(key)
}
3,对于struct数据格式化输出:
per_json, _ := json.MarshalIndent(per, "", " ")
fmt.Println(string(per_json))
对于打印log查看很友好