package main
import (
"fmt"
)
func main() {
//map的声明var m map[int]string
m = make(map[int]string)
var m1 map[int]string = make(map[int]string)
m2 := make(map[int]string)
fmt.Println(m)
fmt.Println(m1)
fmt.Println(m2)
}
package main
import (
"fmt"
)
func main() {
//map的初始化以及赋值
m := make(map[int]string)
a := m[1]
fmt.Println(a)
m[3] = "Three"
b := m[3]
fmt.Println(b)
}
package main
import (
"fmt"
)
func main() {
var m map[int]map[int]string
m = make(map[int]map[int]string)
m[1] = make(map[int]string)
a, ok := m[1][1]
fmt.Println(ok)
if !ok {
m[1][1] = "OK"
}
a, ok = m[1][1]
fmt.Println(a, ok)
}
package main
import (
"fmt"
)
func main() {
sm := make([]map[int]string, 5)
for _, v := range sm {
//v只是一个拷贝,对它的操作不会影响其源值
v = make(map[int]string, 1)
v[1] = "OK"
fmt.Println(v)
}
fmt.Println(sm)
for i := range sm {
//v只是一个拷贝,对它的操作不会影响其源值
sm[i] = make(map[int]string, 1)
sm[i][1] = "OK"
fmt.Println(sm[i])
}
fmt.Println(sm)
}
package main
import (
"fmt"
)
func main() {
//map的无序性
m := map[int]string{1: "a", 2: "b", 3: "c", 4: "d", 5: "e"}
s := make([]int, len(m))
i := 0for k, _ := range m {
s[i] = k
i++
}
//多次执行,每次打印的值都是不一样的
fmt.Println(s)
}
package main
import (
"fmt""sort"//新增sort排序模块
)
func main() {
//map的无序性
m := map[int]string{1: "a", 2: "b", 3: "c", 4: "d", 5: "e"}
s := make([]int, len(m))
i := 0for k, _ := range m {
s[i] = k
i++
}
//对map的key进行排序
sort.Ints(s)
fmt.Println(s)
//曲折对map进行排序for k, _ := range s {
fmt.Println(m[k])
}
}