美文网首页
go编程基础-map

go编程基础-map

作者: 郭某人1 | 来源:发表于2019-01-10 17:31 被阅读4次

map
1.类似于其他语言中的哈希表或者字典,以key-value的形式存储数据;
2.key必须是支持==或!=比较运算的形式,不可以是函数;
3.map查找比线性搜索快很多,比根据索引查找慢很多;
4.map使用make创建,支持 := 的简写方式;
make([keyType]valueType,cap),cap表示容量,可省略, 超出容量时会自动扩容。

一、创建map和操作简单map

m := make(map[int]string)
m[1] = "hello"
a := m[1]
b := m[2]
fmt.Println(a) //"hello"
fmt.Println(b) // 输出为空

m := make(map[int]string)
m[1] = "hello"
delete(m,1)
a := m[1]
fmt.Println(a) //输出为空

二、创建map和操作复杂map

var m map[int]map[int]string = make(map[int]map[int]string)
a, ok := m[2][1] //ok是否初始化
if !ok {
    m[2] = make(map[int]string)//复杂map需要对元素进行初始化,否则会出现运行异常
}
m[2][1] = "ok"
a, ok = m[2][1]
fmt.Println(a, ok)

二、迭代map

sl := make([]map[int]string, 5)
for _, v := range sl {
    v = make(map[int]string, 1)
    v[1] = "ok"
    fmt.Println(v) //map[1:ok]
}
//v只是copy不会影响sl的值
fmt.Println(sl) //[map[] map[] map[] map[] map[]]


sl := make([]map[int]string, 5)
for i := range sl {
    sl[i] = make(map[int]string, 1)
    sl[i][1] = "ok"
    fmt.Println(sl[i]) //map[1:ok]
}
fmt.Println(sl) //[map[1:ok] map[1:ok] map[1:ok] map[1:ok] map[1:ok]]

相关文章

  • go编程基础-map

    map1.类似于其他语言中的哈希表或者字典,以key-value的形式存储数据;2.key必须是支持==或!=比较...

  • 10.map

    Go语言基础之map | Golang Go语言中提供的映射关系容器为map,其内部使用散列表(hash)实现。 ...

  • Go基础——Map

    map声明语法为map[K]V,其中K和V分别对应key和value。map中所有的key都有相同的类型,所有的v...

  • Go语言高并发Map解决方案

    Go语言高并发Map解决方案 Go语言基础库中的map不是并发安全的,不过基于读写锁可以实现线程安全;不过在Go1...

  • 第03天(复合类型)_map的基本使用

    24_map的基本使用.go 25_map赋值.go 26_map遍历.go 27_map删除.go 28_map...

  • Golang资料整理

    视频 郝林-Go语言第一课 Go编程基础 Go Web 基础 Go名库讲解 社区 官网要翻墙 Github--Go...

  • Go编程基础(array、slice、map和struct)

    这篇讲解go语言中数据存储类型array、slice、map和struct,要清楚它们那些是值传递,那些是指针传递...

  • go语言学习

    基础 go的学习,感谢Go By Example、go网络编程与go语言标准库随着学习的深入,此文章持续更新......

  • go基础——map/sync.Map

    注:权作为学习笔记,基于version: 1.14 内容 一 map1.1 数据结构1.2 写入1.3 查找1.4...

  • Map

    常见操作:http://www.runoob.com/go/go-map.html 创建Map 赋值 遍历Map ...

网友评论

      本文标题:go编程基础-map

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