You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

150 lines
2.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"fmt"
"math/rand"
"sort"
)
func main() {
myMap := make(map[string]int)
myMap["song"] = 1
myMap["zhang"] = 2
fmt.Println(myMap)
myMap2 := map[string]string{
"123": "123",
"456": "456",
}
fmt.Println(myMap2)
key, value := IsExist()
if value {
fmt.Printf("%v\n", key)
} else {
fmt.Printf("查无此人: %v\n", key)
}
RangeMap()
DeleteKey("003")
RangeMap2()
MapSlice()
SliceMap()
}
// IsExist 键是否存在
func IsExist() (int, bool) {
fmt.Println("===IsExist===")
mMap := make(map[string]int) //map类型的变量默认初始值为nil需要使用make()函数来分配内存
mMap["张三"] = 333
mMap["李四"] = 444
v, ok := mMap["张三"]
return v, ok
}
// RangeMap 遍历
func RangeMap() {
fmt.Println("===RangeMap===")
rMap := map[string]string{
"001": "张三",
"002": "李四",
"003": "王五",
"004": "周六",
}
for k, v := range rMap {
fmt.Println(k, v)
}
fmt.Println("range key")
for rk := range rMap {
fmt.Println(rk)
}
}
// DeleteKey 删除键
func DeleteKey(key string) {
fmt.Println("===DeleteMap===")
dMap := map[string]string{
"001": "张三",
"002": "李四",
"003": "王五",
"004": "周六",
}
delete(dMap, key)
for k, v := range dMap {
fmt.Println(k, v)
}
}
// RangeMap2 指定顺序遍历
func RangeMap2() {
fmt.Println("===RangeMap2===")
scoreMap := make(map[string]int, 200)
for i := 0; i < 20; i++ {
key := fmt.Sprintf("stu%02d", i)
value := rand.Intn(100)
scoreMap[key] = value
}
//fmt.Println(scoreMap)
//将key存入切片
keys := make([]string, 0, 200)
fmt.Println("排序前")
for key := range scoreMap {
keys = append(keys, key)
fmt.Printf("%v: %v ", key, scoreMap[key])
}
sort.Strings(keys)
fmt.Println("\n排序后")
//for i := 0; i < len(keys); i++ {
// fmt.Printf("%v ", scoreMap[keys[i]])
//}
for _, key := range keys {
fmt.Printf("%v: %v ", key, scoreMap[key])
}
fmt.Println()
}
// MapSlice 元素为map类型的切片
func MapSlice() {
fmt.Println("===元素为map类型的切片===")
//先申明并初始化一个map“切片”
mapSlice := make([]map[string]string, 3)
for index, value := range mapSlice {
fmt.Printf("index: %v, value: %v\n", index, value)
}
//在对切片中的map进行初始化
mapSlice[0] = make(map[string]string, 10)
mapSlice[0]["name"] = "swansong"
mapSlice[0]["age"] = "22"
mapSlice[0]["sex"] = "man"
for index, value := range mapSlice {
fmt.Printf("index: %v, value:%v\n", index, value)
}
}
// SliceMap 值为切片类型的map
func SliceMap() {
fmt.Println("===值为切片的map===")
sliceMap := make(map[string][]string, 3)
//for index, value := range sliceMap {
// fmt.Printf("index: %v, value: %v", index, value)
//}
fmt.Println(sliceMap)
key := "中国"
value, ok := sliceMap[key]
if !ok {
value = make([]string, 0, 2)
}
value = append(value, "北京", "上海")
sliceMap[key] = value
fmt.Println(sliceMap)
}