美文网首页
跟我一起学Golang:Map

跟我一起学Golang:Map

作者: 云枫随笔 | 来源:发表于2019-11-08 13:30 被阅读0次

概念

Golang一种内置结构,形式<key,value>,类似Java中的HashMap或者Python中的dict(字典)。其中key是可比较的,不能为slice,因为slice没有实现比较操作。另外需要注意一点就是map是引用类型,作为参数存在副作用。

操作以及例子

如何创建

使用make,语法格式:make(map[key-type]val-type)

可以在声明的时候初始化:map[key-type]val-type{key:value, ...}

如何修改

赋值:name[key]=val

删除: delete(name, key)

如何访问

直接使用下标:name[key]

带有校验型: val, ok := name[key], ok是false表示key对应的值不存在

例子:

// Maps are Go's built-in associative data type(sometimes called hashes or dicts in other languages)

package main

import "fmt"

func main() {

  // to create an empty map, use the builtin make: make(map[key-type]val-type)

  m := make(map[string]int)

  // set key/value pairs using typical name[key]=val syntax

  m["k1"] = 7

  m["k2"] = 13

  // Printing a map with e.g. fmt.Println will show all of its key/value pairs.

  fmt.Println("map:", m)

  // Get a value for a key with name[key]

  v1 := m["k1"]

  fmt.Println("v1:", v1)

  // the builtin le returns the numbers of key/value pairs when called on a map

  fmt.Println("len:", len(m))

  // the builtin delete removes key/value pairs from a map

  delete(m, "k2")

  fmt.Println("map:", m)

  /**

  * the optional second return value when getting a value from a map

  * indicates if the key was present in the map. This can be used to dismbiguate between missing keys

  * and keys with zero values like 0 or "". Here we didn't need the value itself, so we ignored it with

  * the blank identifer _.

  **/

  _, prs := m["k2"]

  fmt.Println("prs:", prs)

  if !prs {

    fmt.Println("m[\"k2\"] is not exist.")

  }

  // you can also decalre and initialize a new map in the same line with this syntax

  n := map[string]int{"foo": 1, "bar": 2}

  fmt.Println("map:", n)

}

参考资料

https://golang.google.cn/doc/effective_go.html#maps

https://gobyexample.com/maps

相关文章

  • 跟我一起学Golang:Map

    概念 Golang一种内置结构,形式,类似Java中的HashMap或者Python中的di...

  • Go map底层实现

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

  • golang语言map的并发和排序

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

  • map golang

    原文链接:map-GOLANG

  • 我设计的golang面试题

    1 golang中的引用类型 ``` slice、map、channel、interface ``` 2、map如...

  • golang声明一个map数组

    golang 声明一个map数组

  • Golang map

    Golang map map用来存储多个键值对,与java中的map功能相似。 直接声明 需要注意: key,va...

  • golang:map

    什么是map? map是一个可以存储key/value对的一种数据结构,map像slice一样是引用类型,map内...

  • Golang:map

    map golang 中提供映射关系容器为map,其内部使用散列表(hash)实现 map 是一种无序的基于key...

  • Golang——map

    Map是无序的、基于key-value的数据结构,内部使用散列表hash实现。Map是引用类型,声明时是nil,必...

网友评论

      本文标题:跟我一起学Golang:Map

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