Map的声明要求
Map types
The value of an uninitialized map is nil.
A new, empty map value is made using the built-in function make, which takes the map type and an optional capacity hint as arguments:
make(map[string]int)
make(map[string]int, 100)
The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps. A nil map is equivalent to an empty map except that no elements may be added.
Map的创建与初始化
func main (
//第一种
//声明map 产生一个值为nil的map即零值map
//值为nil的map等同于空map,但却不能增加值(与channel相同,slice则除外)
var m1 map[string]interface{}
//m1["tom"] = "cat" //报错:panic: assignment to entry in nil map
fmt.Println(m1)
//零值切片(通过var声明的切片)可以直接使用,无需make创建
//所以,返回空slice,返回nil即可
var s1 []int
fmt.Println(s1) //[]
s1 = append(s1, 1)
fmt.Println(s1) //[1]
//第二种
//使用字面量
m2 := map[string]int{}
m2["tom"] = 12
fmt.Println(m2) //map[tom:12]
//或者
m3 := map[string]int{"tom":12}
fmt.Println(m3) //map[tom:12]
//第三种
//使用make
m4 := make(map[string]string, 10)
m4["tom"] = "cat"
fmt.Println(m4) //map[tom:cat]
)
Map的使用
m5 := map[string]string{}
//增加
m5["tom"] = "dog"
//修改
m5["tom"] = "cat"
//查询
val, ok := m5["tom"]
if !ok {
fmt.Println("无此mao")
return
}
fmt.Println(val)
//删除
delete(m5, "tom")
fmt.Println(m5) //map[]
Map的赋值与值拷贝
//map赋值
//由于map是引用类型,在进行赋值时是不会将指向底层的数据一起拷贝的
//所以,赋值后的数据进行更改,还是会改动底层的数据
m6 := map[string]string{"tom":"cat"}
fmt.Println(m6) //map[tom:cat]
m7 := m6
m7["tome"] = "dog"
fmt.Println(m6) //map[tom:cat tome:dog]
fmt.Println(m7) //map[tom:cat tome:dog]
//map值拷贝
m8 := map[string]string{"tom":"cat", "jack":"mouse"}
m9 := make(map[string]string, len(m8))
for index, value := range m8 {
m9[index] = value
}
fmt.Println(m8) //map[jack:mouse tom:cat]
fmt.Println(m9) //map[jack:mouse tom:cat]
m9["tom"] = "dog"
fmt.Println(m8) //map[jack:mouse tom:cat]
fmt.Println(m9) //map[jack:mouse tom:dog]
网友评论