- Hands-On Full Stack Development with Go
- Mina Andrawos
- 269字
- 2021-07-02 12:33:31
Maps
HashMaps are very popular, and extremely important data structures in any programming language. A map is a collection of key value pairs, where you use the key to obtain the value that corresponds to it. Using maps greatly speeds up your software due to the fact that with a map, retrieving a value through a key is a very quick operation.
In Go, you can declare a map like this:
var myMap map[int]string
The preceding code declares a map where the keys are of type int, and the values are of type string.
You can initialize a map using the make function:
myMap = make(map[int]string)
You can't use a map before you initialize it, otherwise an error will be thrown. Here is another way to initialize a map:
myMap = map[int]string{}
What if you want to initialize the map with some values? You can do this:
myMap = map[int]string{1: "first", 2: "Second", 3: "third"}
To add values to an existing map, you can do this:
myMap[4] = "fourth"
To obtain a value from a map, you can do the following:
//x will hold the value in "myMap" that corresponds to key 4
var x = myMap[4]
You can also check if a key exists in a map by using the following syntax, assuming that your code is inside a function block:
//If the key 5 is not in "myMap", then "ok" will be false
//Otherwise, "ok" will be true, and "x" will be the value
x,ok := myMap[5]
You can delete a value from a map by using the built-in delete function:
//delete key of value 4
delete(myMap,4)
- Advanced Quantitative Finance with C++
- Mastering ServiceStack
- WordPress Plugin Development Cookbook(Second Edition)
- Building Minecraft Server Modifications
- Python深度學(xué)習(xí):模型、方法與實(shí)現(xiàn)
- Java程序員面試筆試寶典(第2版)
- Geospatial Development By Example with Python
- JSP程序設(shè)計(jì)實(shí)例教程(第2版)
- Python期貨量化交易實(shí)戰(zhàn)
- Web開發(fā)新體驗(yàn)
- Elastix Unified Communications Server Cookbook
- 大話程序員:從入門到優(yōu)秀全攻略
- Learning Dynamics NAV Patterns
- 循序漸進(jìn)Vue.js 3前端開發(fā)實(shí)戰(zhàn)
- 嵌入式Linux與物聯(lián)網(wǎng)軟件開發(fā):C語(yǔ)言內(nèi)核深度解析