Go की मूल बातें

Go Maps

Store values under keys: add, read, check, delete and loop in a fixed order.

  • शुरुआती
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • Creating and updating
  • The value, ok form
  • Sorting the keys
stock
"apple"5
"pear"5
"plum"1

Values found by key

A map stores values under keys, so you can find a value quickly by its key. It is Go's version of a dictionary or hash table.

Reading a missing key returns the zero value, so the second result, found, tells you whether the key exists. delete removes a key. A map has no fixed order, so the keys are collected and sorted before printing.

मुख्य बातें

  1. A missing key reads as the zero value.
  2. value, found := m[key] tells you if it exists.
  3. Map order is random: sort the keys.

चलने योग्य Go उदाहरण

Go
कोड चलाएँ →
main.go
package main

import (
	"fmt"
	"sort"
)

func main() {
	stock := map[string]int{"apple": 3, "pear": 5}
	stock["plum"] = 1
	stock["apple"] += 2

	fmt.Println(stock["apple"], len(stock))

	count, found := stock["kiwi"]
	fmt.Println(count, found)

	delete(stock, "pear")

	names := make([]string, 0, len(stock))
	for name := range stock {
		names = append(names, name)
	}
	sort.Strings(names) // map order is random, so sort the keys
	for _, name := range names {
		fmt.Println(name, stock[name])
	}
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
5 3
0 false
apple 5
plum 1

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

अगला: Word Frequency Counter →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज