Learn Golang in Days - Day 12

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

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

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

查看所有标签

猜你喜欢:

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

WEBMASTER技术手册

WEBMASTER技术手册

斯潘奥尔 / 斯潘奥尔 / 清华大学出版社 / 2004-4 / 63.0

本书的第三版升级到Apache PHP和Java Script 最新的版本上。同是它还包含了关于mod_perl更为详尽的信息以及提高Web 性能的方法。书中的内容涉及到HTML4.01、CSS、XML和XSLT、JavaScript1.5 、HTTP1.1、A pache2.0等等。一起来看看 《WEBMASTER技术手册》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具