ข้ามไปยังเนื้อหา

Arrays, Slices และ Maps

ใน JavaScript/TypeScript array เป็นแบบไดนามิกโดยปริยาย และ object ทำหน้าที่เป็น map ส่วน Go แยกเรื่องเหล่านี้ออกจากกัน: arrays ขนาดคงที่, slices แบบไดนามิก (ตัวที่คุณจะใช้ทุกวัน) และ maps

array ของ Go มีขนาดคงที่ฝังอยู่ใน type เลย ในทางปฏิบัติคุณแทบไม่ได้ใช้ array ตรง ๆ ตัวที่ใช้จริงคือ slice — เวอร์ชันไดนามิกที่มี array หนุนอยู่เบื้องหลัง แต่มี length และ capacity ที่ขยายได้ตามต้องการ

TypeScript
// TypeScript — always dynamic
const nums: number[] = [1, 2, 3];
nums.push(4);
console.log(nums.length); // 4
Go
// Go — slice (dynamic)
nums := []int{1, 2, 3}
nums = append(nums, 4)
fmt.Println(len(nums)) // 4
TypeScript
const letters = ["a", "b", "c", "d"];
// slice (non-mutating)
letters.slice(1, 3) // ["b", "c"]
// length
letters.length // 4
Go
letters := []string{"a", "b", "c", "d"}
// slice expression
letters[1:3] // ["b", "c"]
// length
len(letters) // 4

maps ของ Go เหมือนกับ Record<K,V> หรือ Map<K,V> ของ TypeScript คีย์สามารถเป็น type ใดก็ได้ที่เปรียบเทียบกันได้ (comparable)

TypeScript
// TypeScript
const scores: Record<string, number> = {
alice: 95,
bob: 87,
};
scores["carol"] = 91;
delete scores["bob"];
console.log(scores["alice"]);
Go
// Go
scores := map[string]int{
"alice": 95,
"bob": 87,
}
scores["carol"] = 91
delete(scores, "bob")
fmt.Println(scores["alice"])
package main
import (
"fmt"
"sort"
)
func main() {
// Slice
fruits := []string{"banana", "apple", "cherry"}
fruits = append(fruits, "date")
sort.Strings(fruits)
fmt.Println("Fruits:", fruits)
// Map
count := map[string]int{}
words := []string{"go", "is", "fun", "go", "is", "great", "go"}
for _, w := range words {
count[w]++
}
fmt.Println("Word counts:", count)
}
collection type ใดของ Go ที่ขยายตัวได้แบบไดนามิก (เหมือน array ของ JS)?
คุณ append เข้าไปใน slice ใน Go อย่างไร?
การ lookup map แบบสองค่า (val, ok := m[key]) บอกอะไรคุณ?
zero value ที่คืนมาเมื่อเข้าถึงคีย์ int ที่ไม่มีอยู่ใน map คืออะไร?