พื้นฐาน 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

โจทย์ทั้งหมด