Chapter 4: Complex Types

Introduksyon

Labaw sa core types, ang Go kay naay composite types para mag-group ug data: arrays, slices, maps, ug structs. Importante jud ni para makahimo mog tinuod na programs — dili lang hello world.

Collection Types

Tulo ka built-in collection types ang Go: arrays (fixed-size — way usbans), slices (dynamic — flexible), ug maps (key-value — murag diksyonaryo).

Arrays

Ang arrays kay fixed length — parte na sa type. Ang [3]int ug [4]int kay lahi na type. Dili interchangeable.

var nums [3]int
nums[0] = 1
primes := [5]int{2, 3, 5, 7, 11}

Exercise 4.01: Pagdefine ug Array

package main

import "fmt"

func main() {
    days := [5]string{"Mon", "Tue", "Wed", "Thu", "Fri"}
    fmt.Println(days)
}

Comparing Arrays

a := [3]int{1, 2, 3}
b := [3]int{1, 2, 3}
fmt.Println(a == b)  // true

Exercise 4.02: Comparing Arrays

package main

import "fmt"

func main() {
    a := [3]int{10, 20, 30}
    b := [3]int{10, 20, 30}
    fmt.Println("a == b:", a == b)
}

Initializing Arrays Using Keys

arr := [5]int{1: 10, 3: 30}
fmt.Println(arr)  // [0 10 0 30 0]

Exercise 4.03: Keyed Array

package main

import "fmt"

func main() {
    vals := [7]float64{0: 1.0, 3: 2.0, 6: 3.0}
    fmt.Println(vals)
}

Reading from an Array

arr := [3]string{"a", "b", "c"}
fmt.Println(arr[0])

Exercise 4.04: Read from Array

package main

import "fmt"

func main() {
    fruits := [4]string{"apple", "banana", "cherry", "date"}
    fmt.Println("first:", fruits[0])
}

Writing to an Array

arr := [3]int{1, 2, 3}
arr[1] = 99

Exercise 4.05: Write to Array

package main

import "fmt"

func main() {
    temps := [3]float64{23.5, 24.0, 22.8}
    temps[1] = 25.0
    fmt.Println(temps)
}

Looping an Array

arr := [3]string{"a", "b", "c"}
for i, v := range arr {
    fmt.Println(i, v)
}

Exercise 4.06: Loop Array

package main

import "fmt"

func main() {
    nums := [5]int{2, 4, 6, 8, 10}
    for i := 0; i < len(nums); i++ {
        fmt.Println(nums[i] * 2)
    }
}

Modifying Array in Loop

arr := [3]int{1, 2, 3}
for i := range arr {
    arr[i] *= 10
}

Exercise 4.07: Modify Array

package main

import "fmt"

func main() {
    vals := [4]int{5, 10, 15, 20}
    for i := range vals {
        vals[i] *= 2
    }
    fmt.Println(vals)
}

Activity 4.01: Filling an Array

package main

import "fmt"

func main() {
    var squares [10]int
    for i := 0; i < len(squares); i++ {
        squares[i] = (i + 1) * (i + 1)
    }
    fmt.Println(squares)
}

Slice

Ang slices kay dynamic-sized — flexible. Sila ang pinakagamit na collection sa Go. May three parts: pointer sa underlying array, length, ug capacity.

var s []int
s = []int{1, 2, 3}
s = make([]int, 5)
s = make([]int, 3, 5)

Exercise 4.08: Slices

package main

import "fmt"

func main() {
    nums := []int{10, 20, 30}
    nums = append(nums, 40)
    fmt.Println(nums, len(nums), cap(nums))
}

Activity 4.02: Print Name

package main

import "fmt"

func main() {
    name := "Alice"
    fmt.Println("Hello, " + name + "!")
}

Appending Multiple Items

nums := []int{1, 2, 3}
nums = append(nums, 4, 5, 6)

Exercise 4.09: Append Multiple

package main

import "fmt"

func main() {
    scores := []int{85, 90}
    scores = append(scores, 75, 88, 92)
    fmt.Println(scores)
}

Activity 4.03: Locale Checker

package main

import "fmt"

func main() {
    supported := []string{"en-US", "en-GB", "ja-JP"}
    locale := "ja-JP"
    found := false
    for _, l := range supported {
        if l == locale { found = true; break }
    }
    fmt.Println("Found:", found)
}

Slicing

arr := [5]int{0, 1, 2, 3, 4}
s := arr[1:4]  // [1 2 3]

Exercise 4.10: Slicing

package main

import "fmt"

func main() {
    original := []int{1, 2, 3, 4, 5}
    subset := original[1:4]
    original[2] = 99
    fmt.Println("subset:", subset)
}

Slice Internals

Ang slice kay internally usa ka descriptor: pointer + length + capacity. Kung ma-exceed ang capacity sa append, mag-allocate ang Go og bag-o na array — murag upgrade.

Exercise 4.11: Using make

package main

import "fmt"

func main() {
    s := make([]int, 0, 10)
    for i := 0; i < 12; i++ {
        s = append(s, i)
        if cap(s) != cap(s[:len(s)-1]) {
            fmt.Println("realloc at", len(s)-1)
        }
    }
}

Slice Background Behavior

Gamit ug copy() para independent — di magkagubot ang original ug copy:

a := []int{1, 2, 3, 4, 5}
b := make([]int, 3)
copy(b, a[:3])
b[0] = 42
fmt.Println(a[0])  // 1 — wala naapektuhan

Exercise 4.12: copy()

package main

import "fmt"

func main() {
    original := []int{10, 20, 30, 40, 50}
    copied := make([]int, 3)
    copy(copied, original[:3])
    copied[0] = 999
    fmt.Println("original:", original)
    fmt.Println("copied:", copied)
}

Map Fundamentals

ages := map[string]int{"bob": 30}
age, ok := ages["bob"]
delete(ages, "carol")

Exercise 4.13: Map CRUD

package main

import "fmt"

func main() {
    scores := make(map[string]int)
    scores["Alice"] = 95
    fmt.Println(scores)
}

Reading Maps

val, ok := m["b"]
if !ok { fmt.Println("wala ang key") }

Exercise 4.14: Read Map

package main

import "fmt"

func main() {
    phonebook := map[string]string{"Alice": "555-1234"}
    num, ok := phonebook["Carol"]
    if ok { fmt.Println(num) } else { fmt.Println("wala") }
}

Activity 4.04: Slicing the Week

package main

import "fmt"

func main() {
    week := []string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
    fmt.Println(week[1:6])
}

Deleting from Map

delete(m, "a")

Exercise 4.15: Delete Map

package main

import "fmt"

func main() {
    inventory := map[string]int{"apples": 10, "bananas": 5}
    delete(inventory, "bananas")
    fmt.Println(inventory)
}

Activity 4.05: Remove from Slice

package main

import "fmt"

func remove(s []int, i int) []int {
    return append(s[:i], s[i+1:]...)
}

func main() {
    nums := []int{10, 20, 30, 40, 50}
    nums = remove(nums, 2)
    fmt.Println(nums)
}

Simple Custom Types

type Celsius float64
type ID int

Exercise 4.16: Custom Type

package main

import "fmt"

type Miles float64

func main() {
    var d Miles = 26.2
    fmt.Println(d, "miles")
}

Structs

type Person struct {
    Name string
    Age  int
}
p := Person{"Alice", 30}

Exercise 4.17: Structs

package main

import "fmt"

type Book struct {
    Title, Author string
    Year int
}

func main() {
    b := Book{"The Go Language", "Donovan", 2015}
    fmt.Println(b.Title)
}

Comparing Structs

a := Point{1, 2}
b := Point{1, 2}
fmt.Println(a == b)

Exercise 4.18: Compare Structs

package main

import "fmt"

type Rectangle struct { W, H float64 }

func main() {
    r1 := Rectangle{10, 20}
    r2 := Rectangle{10, 20}
    fmt.Println(r1 == r2)
}

Struct Embedding

type Address struct { City string }
type Employee struct {
    Name string
    Address
}
e := Employee{Name: "A", Address: Address{"Tokyo"}}
fmt.Println(e.City)

Exercise 4.19: Embedding

package main

import "fmt"

type Address struct { City string }
type Company struct {
    Name string
    Address
}

func main() {
    c := Company{"Acme", Address{"Manila"}}
    fmt.Println(c.Name, c.City)
}

Type Conversions

var i int = 42
var f float64 = float64(i)

Exercise 4.20: Type Conversion

package main

import "fmt"

func main() {
    var pi float64 = 3.14159
    var truncated int = int(pi)
    fmt.Println(truncated)
}

Type Assertions and any

var v any = "hello"
s := v.(string)
s, ok := v.(string)

Exercise 4.21: Type Assertion

package main

import "fmt"

func main() {
    items := []any{42, "hello"}
    for _, item := range items {
        switch v := item.(type) {
        case int: fmt.Println("int:", v*2)
        case string: fmt.Println("string:", v)
        }
    }
}

Type Switch

var v any = 42
switch val := v.(type) {
case int: fmt.Println("int:", val)
default: fmt.Println("unknown")
}

Exercise 4.22: Type Switch

package main

import "fmt"

func describe(v any) {
    switch val := v.(type) {
    case int: fmt.Println("integer:", val)
    case string: fmt.Println("string:", val)
    default: fmt.Println("unknown")
    }
}

func main() {
    describe(42)
    describe("hello")
}

Activity 4.06: Type Checker

package main

import "fmt"

func main() {
    data := []any{100, "Go", 3.14, true}
    for _, v := range data {
        switch v.(type) {
        case int: fmt.Println("integer")
        case float64: fmt.Println("float")
        case string: fmt.Println("string")
        default: fmt.Printf("other: %T\n", v)
        }
    }
}

Summary