Go-map
map
1.map是key-values结构,引用类型,key可以是基本数据类型和接口,结构体,数组等,
但slice,map,func不可以,因为没法用==判断
values可以是任何类型
2.使用前要make
3.key不能重复,后一个覆盖前一个
4.map是乱序的
//map的声明方式
var a map[string]string
a = make(map[string]string, 2)
a["a1"] = "jinwei"
a["a2"] = "kkk"
a["a3"] = "gggggg"
a["a4"] = "gggggg"
fmt.Println(a)
//第二种
b := make(map[string]string)
b["a1"] = "sss"
fmt.Println(b)
//第三种
c := map[string]string{
"a1": "sss",
"a2": "rrr",
}
c["a3"] = "gg"
fmt.Println(c)
//练习map string:map[string]string
personmap := make(map[string]map[string]string)
personmap["stu1"] = make(map[string]string, 2)
personmap["stu1"]["name"] = "jiwei"
personmap["stu1"]["adr"] = "jiwei"
personmap["stu2"] = make(map[string]string, 2)
personmap["stu2"]["name"] = "jiwei222"
personmap["stu2"]["adr"] = "jiwei2222"
fmt.Println(personmap)
map crud
c := map[string]string{
"a1": "sss",
"a2": "rrr",
}
c["a3"] = "kkkk" //如果存在a1就是修改,如果不存在就是增加a1
//查询
v, ok := c["a1"]
if ok {
fmt.Println("找到了,", v)
} else {
fmt.Println("没找到")
}
//遍历
for k, v := range c {
fmt.Println(k, v)
}
//删除 如果没有此key,不操作也不报错
//删除所有Key,遍历删除或者给他重新map空间,原先的被回收
delete(c, "a1")
fmt.Println(c)
c = make(map[string]string)
fmt.Println(c)
map slice
personslice := make([]map[string]string, 1)
personslice1 := make(map[string]string, 2)
personslice1["name"] = "jinw"
personslice1["addre"] = "addre"
personslice = append(personslice, personslice1)
fmt.Println(personslice)
map排序
map[int]string,将key放入切片,然后使用过sort.Intskeys()排序
然后遍历切片,按key输出map值
var s []int
map1 := make(map[int]int)
map1[1] = 1
map1[2] = 2
map1[3] = 3
for k, _ := range map1 {
s = append(s, k)
}
sort.Ints(s)
fmt.Println(map1)
for _, v := range s {
fmt.Println(map1[v])
}
map是引用类型,引用类型传递机制,函数接手后会直接修改源map数据
func modmap(s map[int]int) {
s[3] = 100
}
func main() {
s := make(map[int]int, 3)
s[1] = 10
s[2] = 11
s[3] = 34
modmap(s)
fmt.Println(s)//map[1:10 2:11 3:100]