Learn Golang in Days - Day 12

栏目: Go · 发布时间: 7年前

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])
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Transcending CSS

Transcending CSS

Andy Clarke、Molly E. Holzschlag / New Riders / November 15, 2006 / $49.99

As the Web evolves to incorporate new standards and the latest browsers offer new possibilities for creative design, the art of creating Web sites is also changing. Few Web designers are experienced p......一起来看看 《Transcending CSS》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具