A map is an unordered collection of key-value pairs, similar to the dictionary in Python.
Declare a map using syntax map[KeyType]ValueType{}
. For example
package main
import "fmt"
func main() {
// Declare an empty map
a := map[string]int{}
a["Steak"] = 450
fmt.Println(a)
// Declare a map with initial value
b := map[string]int{
"Bubble Milk Tea": 55,
"Ice Coffee": 45,
}
fmt.Println(b)
}
The value assigned to a key in a map can be retrieved using the syntax m[key].
If the key does not exists in the map, you’ll get the zero value of the map’s value type.
However, this way might be confused when the key exist but the vale is 0.
To check the key exist in a map or not, we should using syntax value, ok := m[key]
package main
import "fmt"
func main() {
m := map[string]int{
"Bread": 30,
}
fmt.Println("bread's price is", m["Bread"])
// If a key doesn't exist in the map, we get the zero value of the value type
fmt.Println("Salad's price is", m["Salad"])
// key is case sensitive
fmt.Println("Bread's price is", m["bteak"])
// Appropriate way to check key exist or not
price, priceExist := m["Salad"]
if priceExist {
fmt.Println("Salad's price is", price)
} else {
fmt.Println("This store does not sell Salad")
}
}
We can delete a key from a map using the built-in delete()
function
b := map[string]int{
"Bubble Milk Tea": 55,
"Ice Coffee": 45,
}
delete(b, "Ice Coffee")
delete(b, "Cake") // No run time error even key does not exist.
fmt.Println(b)
Similar to array and slice, we can use range to iterate a map
package main
import "fmt"
func main() {
b := map[string]int{
"Bubble Milk Tea": 55,
"Ice Coffee": 45,
}
printMap(b)
}
func printMap(p map[string]int) {
for key, value := range p {
fmt.Printf("The price of %s is %d\n", key, value)
}
}
Similar to slice, map is reference type.
package main
import "fmt"
func main() {
b := map[string]int{
"Bubble Milk Tea": 55,
"Ice Coffee": 45,
}
var c = b
delete(c, "Ice Coffee")
fmt.Println(b) // output is map[Bubble Milk Tea:55]
fmt.Println(c) // output is map[Bubble Milk Tea:55]
updatePrice(c, "Bubble Milk Tea", 60)
fmt.Println(b) // output is map[Bubble Milk Tea:60]
fmt.Println(c) // output is map[Bubble Milk Tea:60]
}
func updatePrice(p map[string]int, key string, newPrice int) {
p[key] = newPrice
}
>>: EP 14: The MenuItem of ListView binds Command in itself Model
今天要跟大家介绍 Zabbix 架构 Zabbix 基本资讯 官网 https://www.zabb...
今天主要要来在app内简易的嵌入一个网页(webview),webview不包含网路浏览器的所有功能...
接下来要在页面上按下按钮跳页 以及按了左边 header icon 回上一页 正所谓有去有回才不会...
作息的重要性 我大部分的时候可以属於夜猫子类型 但几次实验下来发现 熬夜→睡不饱→上班想睡→花比较...
dialog的DEMO 掀开新档 id命名为btnalert onClick从java档来加入 再来...