Arrays, Slices และ Maps
Collections: จาก array ของ JS สู่ slice ของ Go
หัวข้อที่มีชื่อว่า “Collections: จาก array ของ JS สู่ slice ของ Go”ใน JavaScript/TypeScript array เป็นแบบไดนามิกโดยปริยาย และ object ทำหน้าที่เป็น map ส่วน Go แยกเรื่องเหล่านี้ออกจากกัน: arrays ขนาดคงที่, slices แบบไดนามิก (ตัวที่คุณจะใช้ทุกวัน) และ maps
Arrays เทียบกับ Slices
หัวข้อที่มีชื่อว่า “Arrays เทียบกับ Slices”array ของ Go มีขนาดคงที่ฝังอยู่ใน type เลย ในทางปฏิบัติคุณแทบไม่ได้ใช้ array ตรง ๆ ตัวที่ใช้จริงคือ slice — เวอร์ชันไดนามิกที่มี array หนุนอยู่เบื้องหลัง แต่มี length และ capacity ที่ขยายได้ตามต้องการ
// TypeScript — always dynamicconst nums: number[] = [1, 2, 3];nums.push(4);console.log(nums.length); // 4// Go — slice (dynamic)nums := []int{1, 2, 3}nums = append(nums, 4)fmt.Println(len(nums)) // 4การดำเนินการกับ Slice
หัวข้อที่มีชื่อว่า “การดำเนินการกับ Slice”const letters = ["a", "b", "c", "d"];
// slice (non-mutating)letters.slice(1, 3) // ["b", "c"]
// lengthletters.length // 4letters := []string{"a", "b", "c", "d"}
// slice expressionletters[1:3] // ["b", "c"]
// lengthlen(letters) // 4maps ของ Go เหมือนกับ Record<K,V> หรือ Map<K,V> ของ TypeScript คีย์สามารถเป็น type ใดก็ได้ที่เปรียบเทียบกันได้ (comparable)
// TypeScriptconst scores: Record<string, number> = { alice: 95, bob: 87,};scores["carol"] = 91;delete scores["bob"];console.log(scores["alice"]);// Goscores := map[string]int{ "alice": 95, "bob": 87,}scores["carol"] = 91delete(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)}Loading Go runtime (first run only, ~8 MB)…