Learn Golang in Days - Day 12

Learn Golang in Days - Day 12

要点


  • Map是一种无序的键值对的集合。Map最重要的一点是通过Key可以检索到Valu.
  • Map是使用hash表来实现的

定义map


  • 使用map关键字定义
  • 使用make函数定义
// 声明变量,默认map是nil
var map_variable map[key_data_type]value_data_type
var countryMap map[string]string

// 使用make函数来定义
map_variable := make(map[key_data_type]value_data_type)
countryMap := make(map[string]string)

//定义并初始化
var countryMap := map[string]string{"Janpa":"Tokyo","USA":"Washington D.C."}

实例



import "fmt"

func main() {
    // 定义map
    var countrycapitalmap map[string]string
    countrycapitalmap = make(map[string]string)

    countrycapitalmap["france"] = "pairs"
    countrycapitalmap["italy"] = "roma"
    countrycapitalmap["japan"] = "tokya"

    //遍历输出
    for counry := range countrycapitalmap {
        fmt.Printf("countrymap[\"%s\"]=%s\n", counry, countrycapitalmap[counry])
    }

    // 查看元素是否在集合中存在
    capital ,ok := countrycapitalmap["france"]
    if(ok){
        fmt.Printf("法国的首都是%s\n", capital)
    }else{
        fmt.Printf("集合中未找到寻找的键\n")
    }

    capital ,ok = countrycapitalmap["德国"]
    if(ok){
        fmt.Printf("德国的首都是%s\n", capital)
    }else{
        fmt.Printf("集合中未找到寻找的键德国\n")
    }
}

delete() 函数,删除元素


  • delete() 函数删除集合中的元素,参数为map和其对应的键
  • delete(Map, item)
package main

import "fmt"

func main() {
    // 定义map
    var countryMap map[string]string
    countryMap = make(map[string]string)

    countryMap1 := map[string]string{"Japan": "Tokyo", "China": "Beijing"}
    countryMap["Japan"] = "Tokyo"

    //遍历
    fmt.Println("------ 删除前 遍历 -----------")
    for country := range countryMap1 {
        fmt.Printf("countryMap1[%s]=%s\n", country, countryMap1[country])
    }

    // 删除元素
    delete(countryMap1, "China")

    //遍历
    fmt.Println("------ 删除后 遍历 -----------")
    for country := range countryMap1 {
        fmt.Printf("countryMap1[%s]=%s\n", country, countryMap1[country])
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_34407348/article/details/87655083