17.Go_Set(集合)_Map

Go 集合
Map是一种无序的键值对的集合
通过 key 来快速检索数据,key 类似于索引,指向数据的值。
Map 是无序的,无法决定它的返回顺序,这是因为 Map 是使用 hash 表来实现的。
定义Map
使用内建函数make也可以使用map关键字来定义map:
//声明变量,默认 map 是 nil
var map_variable map[key_data_type]value_data_type
//使用 make 函数
map_variable := make(map[key_data_type]value_data_type)
如果不初始化 map,那么就会创建一个 nil map。nil map 不能用来存放键值对
例如:
package main
import "fmt"
func main() {
    var country map[string]string
    //创建集合
    country = make(map[string]string)
    //map插入key-value对,各个国家对应的首都
    country["France"] = "Paris"
    country["Italy"] = "Rome"
    country["Japan"] = "Tokyo"
    country["India"] = "New Delhi"
    //使用可以输出map值
    for country1 := range country{
        fmt.Println("capital of ",country1,"is",country[country1])
    }
    captial,ok := country["China"]
    //OK是Ture 则存在,否则不存在
    if(ok){
        fmt.Printf("capital of %d\n",captial)
    }else {
        fmt.Printf("capital of  not present")
    }
}
运行结果:
capital of  Italy is Rome
capital of  Japan is Tokyo
capital of  India is New Delhi
capital of  France is Paris
capital of  not present
delete()函数
delete() 函数用于删除集合的元素, 参数为 map 和其对应的 key。
例如:
package main
import "fmt"
func main() {
    //创建map
    country := map[string] string{
        "France":"Paris",
        "Italy":"Rome",
        "Japan":"Tokyo",
        "India":"New Delhi",
    }
    fmt.Println("原始map")
    //打印map
    for country1 := range  country{
        fmt.Println("capital of ",country1,"is",country[country1])
    }
    //删除元素
    delete(country,"France")
    fmt.Println("删除元素后map")
    //打印map
    for country1 := range  country{
        fmt.Println("capital of ",country1,"is",country[country1])
    }
}
运行结果:
原始map
capital of  France is Paris
capital of  Italy is Rome
capital of  Japan is Tokyo
capital of  India is New Delhi
删除元素后map
capital of  Italy is Rome
capital of  Japan is Tokyo
capital of  India is New Delhi

你可能感兴趣的:(17.Go_Set(集合)_Map)