iT邦幫忙

2021 iThome 鐵人賽

DAY 11
0

A map is an unordered collection of key-value pairs, similar to the dictionary in Python.

Declaring a map

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)

}

Access a key-value pair in a map

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")
	}

}

Delete a key in a map

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)

Iterating over a map

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)
	}
}

Map is Reference Type

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
}

上一篇
[Golang] Pointer
系列文
"GoDevOps": Learn DevOps Tools with Go11
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言