Sugdon ta ug tarong: naay bugs? Normal ra. Bisan si Linus Torvalds naay bugs (ayaw lang ingni siya). Anhi nga chapter, mangita ta sa bug nga mas tago pa kaysa feelings sa imong crush. Atong gamiton ang fmt, log, type checking sa runtime, ug uban pang paagi para di ka mag-antos ug debugging sa alas-3 sa kadlawon.
Wala jud code na 100% bug-free. Sige, hagita ko. Dili jud na mahitabo. Pero naay practices na makatabang: test early ug often, i-handle ang tanang errors (ayaw nang _), gamit ug logging, magsulat ug gagmay na functions (dili nang isa ka function 500 lines), ug gamit ang Go toolchain (go vet, go test).
Magsulat ug pila lang ka linya, run dayon, verify ang output. Ayaw nang magsulat ug 200 lines unya mag wonder kung ngano wala nag-work. Parehas rag nagluto — tilawi daan, ayaw nang human pa luto bago ka makatilaw. Gamit ug go run para sa quick iterations.
Maayo kay ang Go kay naay built-in testing framework — wala nang mag-install2 ug extra tools. Paghimo ug _test.go files naay TestXxx functions. Kung walay test, walay peace of mind:
// File: math.go
package math
func Add(a, b int) int {
return a + b
}
// File: math_test.go
package math
import "testing"
func TestAdd(t *testing.T) {
got := Add(2, 3)
want := 5
if got != want {
t.Errorf("Add(2,3) = %d; want %d", got, want)
}
}
Run with: go test ./...
Number one nga rason sa production downtime? Gi-ignore ang error. f, _ := os.Open("file.txt") — pagka-AMBA. Check jud nang return values. Gamit ang _ lang kung intentionally gyud nimo gi-ignore (rare kaayo — like 0.1% ra):
// Sayop — gi-ignore ang error
f, _ := os.Open("file.txt")
// Sakto
f, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
Gamit ug log package imbes fmt.Println para mas professional imong debugging. Naa timestamps, pwede sa files, ug naay levels. Mura rag naka-uniform imong logs — dili magkagubot:
import "log"
func main() {
log.Println("starting application")
log.Printf("user %s logged in", "alice")
}
Output naay timestamp: 2024/01/15 10:30:00 starting application
Ang fmt package kay imong best friend sa debugging. Nagprovide ug daghang printing functions para makita nimo kung unsa'y nahitabo sa imong code: Println, Printf, Sprintf — naa na tanan:
fmt.Println("simple print with newline")
fmt.Printf("formatted: %s %d\n", "hello", 42)
fmt.Sprintf("returns a string instead of printing")
Goal: Gamit ug fmt.Println para i-debug ang calculation pinaagi sa pag-print ug intermediate values.
package main
import "fmt"
func main() {
x := 10
y := 3
fmt.Println("x =", x)
fmt.Println("y =", y)
fmt.Println("x / y =", x/y) // integer division
fmt.Println("x % y =", x%y) // remainder
}
fmt.Printf kay magamit ug format verbs — murag shortcut sa keyboard. %v (default), %d (integer), %s (string), %f (float), %t (bool), %T (type). Importante na sila:
name := "Alice"
age := 30
height := 5.6
fmt.Printf("Name: %s, Age: %d, Height: %.1f\n", name, age, height)
// Output: Name: Alice, Age: 30, Height: 5.6
fmt.Printf("%%v (default): %v\n", 255)
fmt.Printf("%%d (decimal): %d\n", 255)
fmt.Printf("%%b (binary): %b\n", 255)
fmt.Printf("%%x (hex): %x\n", 255)
fmt.Printf("%%o (octal): %o\n", 255)
fmt.Printf("%%f (float): %f\n", 3.14)
fmt.Printf("%%.2f (2 decimals): %.2f\n", 3.14159)
fmt.Printf("%%6d (width 6): %6d\n", 42)
fmt.Printf("%%-6d (left align): %-6d\n", 42)
Goal: I-print ang parehas na number sa decimal, binary, hexadecimal, ug octal.
package main
import "fmt"
func main() {
n := 42
fmt.Printf("decimal: %d\n", n)
fmt.Printf("binary: %b\n", n)
fmt.Printf("hex: %x\n", n)
fmt.Printf("octal: %o\n", n)
fmt.Printf("char: %c\n", n) // '*'
}
Bai, kung naay sayop, ayaw dayon inasal. Sugdi sa pinakasimple — mag-print ug values. Ibutang ug fmt.Printf or log.Println para makita nimo kung unsa juy nahitabo. Mura rag nangita kag nawala sa imong kwarto — suga sa, before ka mag-alsa ug muwebles. Check para sa:
<= diay ni?Gamit ug %T para makita ang type sa variable sa runtime — mabuko na ang nagtago2 nga type. Ug %#v para Go-syntax representation, kung gusto nimo makita ang exact structure:
var v any = []int{1, 2, 3}
fmt.Printf("type: %T\n", v) // []int
fmt.Printf("go: %#v\n", v) // []int{1, 2, 3}
Goal: I-debug ang struct pinaagi sa pag-print ug Go representation.
package main
import "fmt"
type Product struct {
Name string
Price float64
Tags []string
}
func main() {
p := Product{"Laptop", 999.99, []string{"electronics", "tech"}}
fmt.Printf("%%v: %v\n", p)
fmt.Printf("%%+v: %+v\n", p)
fmt.Printf("%%#v: %#v\n", p)
}
Ang Go log package kay mas daghan feature kaysa fmt — naa timestamps (praktikal), pwede magsulat sa files, ug support ug levels. Mura rag upgrade from tricycle to aircon na taxi. Configure ug custom logger:
import (
"log"
"os"
)
func main() {
file, _ := os.Create("app.log")
defer file.Close()
logger := log.New(file, "DEBUG: ", log.Ldate|log.Ltime|log.Lshortfile)
logger.Println("this goes to the log file")
logger.Printf("user %s logged in", "alice")
}
log.Fatal kay mag-print ug message, dayon mag-call ug os.Exit(1) — wala nang patawad. Gamit para sa critical failures na wala nay lain mahimo. Mura rag naka-fatal error ang imong ATM — wala nay lain, adto sa bangko:
f, err := os.Open("config.json")
if err != nil {
log.Fatalf("cannot open config: %v", err)
}
defer f.Close()
log.Panic kay parehas pero mag-print pa ug stack trace ug mag-call ug panic.
Goal: Paghimo ug program na mag-validate ug SSN format (XXX-XX-XXXX) ug mogamit ug logging para sa debugging.
package main
import (
"fmt"
"log"
"regexp"
)
func validateSSN(ssn string) bool {
log.Printf("validating SSN: %s", ssn)
if len(ssn) != 11 {
log.Println("invalid length")
return false
}
matched, _ := regexp.MatchString(`^\d{3}-\d{2}-\d{4}$`, ssn)
if !matched {
log.Println("format mismatch")
return false
}
log.Println("SSN is valid")
return true
}
func main() {
testSSNs := []string{"123-45-6789", "12-345-6789", "abc-def-ghij", "000-00-0000"}
for _, ssn := range testSSNs {
if validateSSN(ssn) {
fmt.Printf("%s: valid\n", ssn)
} else {
fmt.Printf("%s: invalid\n", ssn)
}
}
}
fmt.Printf na may format verbs (%v, %d, %s, %T, %#v) para mag-inspect ug valueslog imbes fmt para production debugging (timestamps, file output)log.Fatal para critical failures, log.Panic para unexpected statestesting package