[Go] Map
2023-09-14 08:59:12 时间
A Go map type looks like this:
map[KeyType]ValueType
This variable m
is a map of string keys to int values:
var m map[string]int
Map types are reference types, like pointers or slices, and so the value of m
above is nil
; it doesn’t point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don’t do that. To initialize a map, use the built in make
function:
m = make(map[string]int)
Setup a Map with default values:
package main
import "fmt"
func main() {
users := map[int]string{
1: "john",
2: "Joe",
}
fmt.Println(users[1]) // john
}
Check value exists:
package main
import "fmt"
func main() {
users := map[int]string{
1: "john",
2: "Joe",
}
fmt.Println(users[1]) // john
thirdUser, ok := users[3]
fmt.Println(thirdUser, ok) // <empty> false
if _, ok := users[3]; ok {
fmt.Println("User exists")
} else {
fmt.Println("User does not exists") // print out
}
}
delete prop:
delete(users, 1)
相关文章
- go语言实现限流器
- 【Go命令教程】9. go list
- Atitit golang开发环境搭建 目录 1. 编辑helo.go1 1.1. 调试编译1 2. Ide选择liteide2 3. 问题解决2 4. 附录2 4.1. Go语言标准库常
- 【Go基础】一篇文章带你了解 — map
- 【Go】go实现 — 冒泡排序算法
- go下载地址
- go-009-函数
- 387集Go语言核心编程培训视频教材整理 | 面向对象编程(二)
- Linux系统之部署Go语言开发运行环境
- go语言笔记——map map 默认是无序的,不管是按照 key 还是按照 value 默认都不排序
- GO语言教程(一)Linux( Centos)下Go的安装, 以及HelloWorld
- Go语言参数校验(go-playground / validator)——基本使用
- Go语言中new()和 make()的区别详解
- gin框架用go-redis+redsync实现分布式锁
- 【博客549】利用go的lazy load实现defer的延迟判断
- Go 复合数据类型 原生map类型的实现机制是怎样的?
- Go 函数 函数类型和作为函数返回值