Chapter 19: Special Features

Introduksyon

Ani na ang final chapter. Last na jud. Go's advanced ug lesser-known features: build constraints (conditional compilation), reflection, deep comparison, pattern-based testing, unsafe package, ug cgo para calling C code. Kung naabot kas diri, congrats — wa kay plano mo-undang.

Build Constraints

Ang build constraints nag-control kung unsa na files ang i-include sa compilation based sa OS, architecture, or custom tags. I-place as comments sa taas sa file. Murag "VIP section" sa imong code — specific files lang ang musulod sa specific platforms:

//go:build linux
package main

// This file only compiles on Linux

//go:build !windows
// This file compiles on everything except Windows

Build Tags

Ang custom build tags nag-enable ug conditional compilation. I-define ang tag gamit //go:build tagname ug i-include gamit -tags. Kung gusto kag production vs development build, tags imong amigo:

// File: production.go
//go:build production

package main

func init() {
    config.Load("production.conf")
}

// File: development.go
//go:build !production

package main

func init() {
    config.Load("development.conf")
}

// Build for production: go build -tags production
// Default (no tag): uses development.go

Filenames

Ang Go nagamit pud ug filename conventions para conditional compilation. Ang file na gi-name *_linux.go kay sa Linux lang, *_windows.go sa Windows, *_amd64.go sa 64-bit x86. Dili naman kailangan ug build tags kung filename ra:

config_linux.go     // Linux only
config_windows.go   // Windows only
config_darwin.go    // macOS only
utils_amd64.go      // 64-bit x86 only

Reflection

Ang reflection nag-allow nimo mag-inspect ug types ug values sa runtime gamit ang reflect package. Useful para generic operations pero gamiton ug tarong — prefer interfaces ug generics kung possible. Ang reflection kay powerful pero mahal — murag magpa-spa, nindot pero naay bayad (performance-wise):

import "reflect"

var x float64 = 3.14
t := reflect.TypeOf(x)
v := reflect.ValueOf(x)

fmt.Println(t.Name())       // float64
fmt.Println(t.Kind())       // float64
fmt.Println(v.Float())      // 3.14
fmt.Println(v.CanSet())     // false (v is a copy)

TypeOf and ValueOf

reflect.TypeOf nag-return ug type information. reflect.ValueOf nag-return ug value ug nag-allow ug inspection/manipulation. Magamit ni nimo kung gusto ka mag-generic na function na mu-work sa bisan unsa na type:

type User struct {
    Name string
    Age  int
}

u := User{"Alice", 30}
t := reflect.TypeOf(u)
v := reflect.ValueOf(u)

fmt.Println("Type:", t.Name())          // User
fmt.Println("Fields:", t.NumField())    // 2

for i := 0; i < t.NumField(); i++ {
    field := t.Field(i)
    value := v.Field(i)
    fmt.Printf("  %s: %v (%s)\n", field.Name, value.Interface(), field.Type)
}

// Modify via pointer
vp := reflect.ValueOf(&u).Elem()
vp.Field(0).SetString("Bob")
fmt.Println(u)  // {Bob 30}

Exercise 19.01: Using Reflection

Goal: Magsulat ug function na mu-kuha ug bisan unsa na struct ug i-print ang field names ug values gamit reflection. Dili na magsulat ug separate na function para kada struct type:

package main

import (
    "fmt"
    "reflect"
)

type Product struct {
    Name  string
    Price float64
    Stock int
}

func inspect(v any) {
    rv := reflect.ValueOf(v)
    rt := reflect.TypeOf(v)

    if rt.Kind() == reflect.Struct {
        fmt.Println("Fields of", rt.Name())
        for i := 0; i < rt.NumField(); i++ {
            fmt.Printf("  %s: %v\n", rt.Field(i).Name, rv.Field(i).Interface())
        }
    }
}

func main() {
    p := Product{"Laptop", 999.99, 10}
    inspect(p)
}

Activity 19.01: Defining Build Constraints Using Filenames

Goal: Paghimo ug platform-specific files na mu-print ug lain messages sa lain operating systems. I-let Go ang mag-decide kung unsa ang gamiton based sa imong OS:

// File: os_darwin.go
package main

func osName() string {
    return "macOS"
}

// File: os_linux.go
package main

func osName() string {
    return "Linux"
}

// File: os_windows.go
package main

func osName() string {
    return "Windows"
}

// File: main.go
package main

import "fmt"

func main() {
    fmt.Println("Running on", osName())
}

// Build on each platform picks the right file automatically

DeepEqual

reflect.DeepEqual nag-compare ug two values recursively — useful para mag-compare ug slices, maps, ug structs na dili macompare sa ==. Dili pwede ang == sa slice, pero DeepEqual kay kaya:

import "reflect"

a := []int{1, 2, 3}
b := []int{1, 2, 3}
c := []int{3, 2, 1}

fmt.Println(reflect.DeepEqual(a, b))  // true
fmt.Println(reflect.DeepEqual(a, c))  // false (order matters)

m1 := map[string]int{"a": 1, "b": 2}
m2 := map[string]int{"b": 2, "a": 1}
fmt.Println(reflect.DeepEqual(m1, m2))  // true (map order doesn't matter)

Wildcard Pattern

Ang Go test nagsupport ug wildcard/pattern matching para mag-run ug specific tests. Gamit ug -run na may regex pattern. Kung gusto ka lang mag-run ug specific tests, ayawg sige ug komentohan ang uban — gamit ug -run:

go test -run TestAdd           # run only TestAdd
go test -run "TestAdd|TestSub"  # run TestAdd and TestSub
go test -run "^Test"            # all tests starting with Test
go test -run "TestUser" ./...   # all TestUser across packages
go test -v -run "Test"          # verbose matching

// In the test file:
func TestAdd(t *testing.T) { /* ... */ }
func TestSub(t *testing.T) { /* ... */ }
func TestUserCreate(t *testing.T) { /* ... */ }

The unsafe Package

Ang unsafe package nagprovide ug operations na nag-bypass sa Go type safety. Gamit lang kung necessary jud — interfacing sa C code, shared memory, or performance-critical low-level operations. Ang name palang daan, "unsafe" — so warning jud. Gamit sa imong sariling risk:

import "unsafe"

var x int32 = 42
// Get the memory size of a type
fmt.Println(unsafe.Sizeof(x))         // 4
fmt.Println(unsafe.Alignof(x))        // 4

// Pointer arithmetic (discouraged)
var arr [3]int32
ptr := unsafe.Pointer(&arr[0])
// Move to the next element by adding the size
next := unsafe.Pointer(uintptr(ptr) + unsafe.Sizeof(arr[0]))

Ang Go memory safety guarantee kay void kung nagamit ug unsafe. Ang garbage collector pwede mag-move ug values, pwedeng ma-invalid ang uintptr pointers. Kung di ka sure, ayaw lang — di ni para sa imo.

Exercise 19.02: Using cgo with unsafe

Goal: Mag-call ug C function gikan sa Go gamit cgo ug unsafe package. Kung naa kay legacy C library nga gusto nimo gamiton sa Go, cgo imong katapat. Pero expect lang — mag-install kag C compiler, maghulat sa compilation:

package main

/*
#include 
#include 

void greet(const char* name) {
    printf("Hello, %s!\n", name);
}
*/
import "C"
import "unsafe"

func main() {
    name := C.CString("from CGO")
    defer C.free(unsafe.Pointer(name))
    C.greet(name)
}

// Build with: go build
// Requires a C compiler (gcc) to be installed

Activity 19.02: Using Wildcard with Go Test

Goal: Magsulat ug multiple test functions ug mag-run ug specific subsets gamit pattern matching. Selective testing — dili mag-run sa tanan kung isa lang imong gusto:

// File: math_test.go
package main

import "testing"

func TestAddPositive(t *testing.T) {
    if add(2, 3) != 5 {
        t.Error("2+3 should be 5")
    }
}

func TestAddNegative(t *testing.T) {
    if add(-2, -3) != -5 {
        t.Error("-2+-3 should be -5")
    }
}

func TestSubPositive(t *testing.T) {
    if sub(5, 3) != 2 {
        t.Error("5-3 should be 2")
    }
}

func TestSubNegative(t *testing.T) {
    if sub(3, 5) != -2 {
        t.Error("3-5 should be -2")
    }
}

// Run:
// go test -run "TestAdd"         # run all Add tests
// go test -run "TestAdd|TestSub" # run Add and Sub tests
// go test -run "Positive"        # run tests with Positive in name
// go test -v -run "."            # run all tests verbosely

Summary

Ani na ang final chapter sa Go special features:

Nahuman na nimo ang full Go tutorial — gikan sa variables ug control flow padulong sa concurrency, HTTP servers, security, ug advanced features. Seryoso, congrats jud. Ang best way para ma-solidify ang skills kay maghimo ug real projects. Good luck, ug padayon sa coding. Mangita ug problema, i-solve, ug balik-balika. See you around.