Arrays, Slices & Maps
Collections: from JS arrays to Go slices
Section titled “Collections: from JS arrays to Go slices”In JavaScript/TypeScript, arrays are dynamic by default and objects serve as maps. Go separates these concerns: fixed-size arrays, dynamic slices (the one you’ll use daily), and maps.
Arrays vs Slices
Section titled “Arrays vs Slices”Go arrays have a fixed size baked into the type. You’ll rarely use them directly. Slices are the dynamic, flexible version — backed by an array but with a length and capacity that grow as needed.
// 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)) // 4Slice operations
Section titled “Slice operations”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) // 4Go maps are like TypeScript Record<K,V> or Map<K,V>. Keys can be any comparable type.
// 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"])Try it
Section titled “Try it”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)…