美文网首页
golang集合map

golang集合map

作者: 程序小白菜 | 来源:发表于2019-12-30 15:21 被阅读0次

定义

map 是一种无序的键值对的集合。map最重要的一点是通过 key 来快速检索数据,key 类似于索引,指向数据的值。map是一种集合,所以我们可以像迭代数组和切片那样迭代它。不过,map是无序的,我们无法决定它的返回顺序,这是因为 map是使用 hash 表来实现的

map的声明

一般定义 map 的方法是: map[<from type>]<to type>

/* 声明变量,默认 map 是 nil */
var map_variable map[key_data_type]value_data_type

    /*创建集合 */
    var countryCapitalMap map[string]string 
    countryCapitalMap = make(map[string]string)
    /* map插入key - value对,各个国家对应的首都 */
    countryCapitalMap [ "France" ] = "巴黎"
    countryCapitalMap [ "Italy" ] = "罗马"
    countryCapitalMap [ "Japan" ] = "东京"
    countryCapitalMap [ "India " ] = "新德里"

/* 使用 make 函数 */
map_variable := make(map[key_data_type]value_data_type)

monthdays := map[ string] int {
    "Jan": 31, "Feb": 28, "Mar": 31,
    "Apr": 30, "May": 31, "Jun": 30,
    "Jul": 31, "Aug": 31, "Sep": 30,
    "Oct": 31, "Nov": 30, "Dec": 31, //逗号是必须的
}

delete() 函数

delete() 函数用于删除集合的元素, 参数为 map 和其对应的 key

package main

import "fmt"

func main() {
        /* 创建map */
        countryCapitalMap := map[string]string{"France": "Paris", "Italy": "Rome", "Japan": "Tokyo", "India": "New delhi"}

        fmt.Println("原始地图")

        /* 打印地图 */
        for country := range countryCapitalMap {
                fmt.Println(country, "首都是", countryCapitalMap [ country ])
        }

        /*删除元素*/ 
        delete(countryCapitalMap, "France")
        fmt.Println("法国条目被删除")

        fmt.Println("删除元素后地图")

        /*打印地图*/
        for country := range countryCapitalMap {
                fmt.Println(country, "首都是", countryCapitalMap [ country ])
        }
}

相关文章

  • golang集合map

    定义 map 是一种无序的键值对的集合。map最重要的一点是通过 key 来快速检索数据,key 类似于索引,指向...

  • 剖析golang map的实现

    [TOC] 本文参考的是golang 1.10源码实现。 golang中map是一个kv对集合。底层使用hash ...

  • Learn Golang in Days - Day 12

    Learn Golang in Days - Day 12 要点 Map是一种无序的键值对的集合。Map最重要的一...

  • hive使用struct、map与array类型字段

    hive支持struct,map,array三种集合类型 struct 与C语言、golang中的struct类似...

  • Go map底层实现

    golang map源码详解Golang map 如何进行删除操作?

  • Go 通过 map 实现 set

    众所周知,Golang 自带的数据结构是没有set集合的。 那么,今天我们通过map来实现一个不重复的set集合。...

  • 2019-01-03

    Map集合 Map集合 1.1Map集合概念 Map集合是一种存放关系对象的对象的双列集合。 1.2Map集合的常...

  • golang语言map的并发和排序

    golang语言map的并发和排序 map的并发问题 golang缺省的map不是thread safe的,如果存...

  • Golang学习笔记之集合(map)

    Map 是一种无序的键值对的集合。Map 最重要的一点是通过 key 来快速检索数据,key 类似于索引,指向数据...

  • 2019-01-13

    基于Map集合重点整理 Map集合 1.1Map集合概念 Map集合是一种存放关系对象的对象的双列集合。 1.2M...

网友评论

      本文标题:golang集合map

      本文链接:https://www.haomeiwen.com/subject/ytrmoctx.html