Chapter 7: Interfaces

Introduksyon

Ang interfaces kay kung gusto kag chika lang — Go style. Ginasulti nila kung unsa'y kaya sa imong type, dili kung unsa gyud siya. Ug ang nice sa Go, implicit ra — basta naa lang sa imong type ang required methods, goods na. Wala nang "implements" na keyword nga dugang2 ra.

Interface

Ang interface type kay set lang sa method signatures — murag wishlist. Bisan unsa na type basta naay tanang required methods, automatic satisfied na. Walay additional paperwork:

type Stringer interface {
    String() string
}

Pagdefine ug Interface

type Speaker interface {
    Speak() string
}

Pag-implementar ug Interface

Implicit ra ang implementation. Wala nang implements na keyword. Mura rag "no need to tell me you're a tambay — kita ra nako sa imong gibuhat":

type Dog struct{ Name string }
func (d Dog) Speak() string { return "Woof!" }

type Cat struct{ Name string }
func (c Cat) Speak() string { return "Meow!" }

var s Speaker = Dog{"Buddy"}
fmt.Println(s.Speak())

Advantages of Implicit Interfaces

Exercise 7.01: Implementing an Interface

package main

import "fmt"

type Notifier interface { Notify() string }

type Email struct { Address, Message string }
func (e Email) Notify() string {
    return "Email to " + e.Address + ": " + e.Message
}

type SMS struct { Phone, Message string }
func (s SMS) Notify() string {
    return "SMS to " + s.Phone + ": " + s.Message
}

func sendAll(notifiers []Notifier) {
    for _, n := range notifiers { fmt.Println(n.Notify()) }
}

func main() {
    sendAll([]Notifier{
        Email{"alice@example.com", "Welcome!"},
        SMS{"555-1234", "Your code is 1234"},
    })
}

Duck Typing

"Kung mu-itik ug mu-quack, itik jud na." — Go version: "Kung naay Quack() string method, Quacker na." Simple ra. Bisan tao pa na nagpakaarong itik, mu-work gyapon. Dili ta manghukom sa pagkatawo, sa methods lang:

type Quacker interface { Quack() string }

type Duck struct{}
func (Duck) Quack() string { return "Quack!" }

type Person struct{}
func (Person) Quack() string { return "Nagpaka-arong itik" }

func makeItQuack(q Quacker) { fmt.Println(q.Quack()) }

func main() {
    makeItQuack(Duck{})
    makeItQuack(Person{})
}

Polymorphism

Ang interfaces kay nag-enable ug polymorphism — isa ka function, daghang types. Mura rag "salamat" — depende sa naghatag, sa tindera, sa kaila nimo, pero parehas rag meaning:

type Shape interface { Area() float64 }

type Circle struct{ R float64 }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }

type Rect struct{ W, H float64 }
func (r Rect) Area() float64 { return r.W * r.H }

func printArea(s Shape) { fmt.Printf("Area: %.2f\n", s.Area()) }

Exercise 7.02: Area of Different Shapes

package main

import (
    "fmt"
    "math"
)

type Shape interface { Area() float64 }

type Circle struct{ R float64 }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }

type Rect struct{ W, H float64 }
func (r Rect) Area() float64 { return r.W * r.H }

type Triangle struct{ Base, Height float64 }
func (t Triangle) Area() float64 { return 0.5 * t.Base * t.Height }

func totalArea(shapes []Shape) float64 {
    total := 0.0
    for _, s := range shapes { total += s.Area() }
    return total
}

func main() {
    shapes := []Shape{Circle{3}, Rect{4, 5}, Triangle{6, 8}}
    fmt.Printf("Total: %.2f\n", totalArea(shapes))
}

Accept Interfaces, Return Structs

Common na sa Go: accept interfaces, return structs. Dapat flexible ka sa gihatag sa imoha, pero concrete ang imong i-uli. Mura rag mag-commute — bisan unsang sakyanan (jeep, bus, tricycle) basta makadala sa imoha, pero kung muli ka, imong tiil ra jud:

func Process(r io.Reader) error {
    data, _ := io.ReadAll(r)
    // process...
    return nil
}

func NewService() *Service { return &Service{} }

Empty interface{}

Ang empty interface (any) kay way method — literally every type mu-satisfy. Mura rag "bisag unsa, dawaton ra nako." Pero ayaw abusar ha:

var v any = 42
v = "hello"
v = struct{ Name string }{"Alice"}

func printAny(v any) {
    fmt.Printf("value: %v, type: %T\n", v, v)
}

Type Assertion and Switches

var v any = "hello world"

s := v.(string)         // mag-panic kung dili string
s, ok := v.(string)     // safe — ok false kung wrong type

switch val := v.(type) {
case string: fmt.Println("string:", val)
case int:    fmt.Println("int:", val)
}

Exercise 7.03: Analyzing any Data

package main

import "fmt"

func analyze(items []any) {
    s, i, f, o := 0, 0, 0, 0
    for _, item := range items {
        switch item.(type) {
        case string: s++
        case int, int32, int64: i++
        case float32, float64: f++
        default: o++
        }
    }
    fmt.Printf("Str:%d Int:%d Float:%d Other:%d\n", s, i, f, o)
}

func main() {
    analyze([]any{"go", 42, 3.14, true, "lang", 100, 2.71, 'A'})
}

Activity 7.01: Pay and Performance Review

package main

import "fmt"

type Employee interface { Pay() float64; Review() string }

type FullTime struct{ Name string; Salary float64 }
func (f FullTime) Pay() float64 { return f.Salary / 12 }
func (f FullTime) Review() string { return f.Name + ": Excellent" }

type Contractor struct{ Name string; Rate, Hours float64 }
func (c Contractor) Pay() float64 { return c.Rate * c.Hours }
func (c Contractor) Review() string { return c.Name + ": Pending review" }

func processPayroll(emps []Employee) {
    total := 0.0
    for _, e := range emps {
        fmt.Println(e.Review())
        total += e.Pay()
    }
    fmt.Printf("Total: $%.2f\n", total)
}

func main() {
    processPayroll([]Employee{
        FullTime{"Alice", 120000},
        Contractor{"Bob", 50, 160},
    })
}

Summary