Thuta Learning
Go
AdvancedProgrammingအခြေခံ

Generics & Type Constraints

Goသင်ခန်းစာ 1530 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • func Name[T Constraint](...) ပုံစံနဲ့ generic function ရေးပြီး type inference နဲ့ ခေါ်နိုင်ဖို့
  • any, comparable, cmp.Ordered တစ်ခုချင်းစီက ဘာ operator တွေ ခွင့်ပြုလဲ ခွဲခြားနိုင်ဖို့
  • ~int လို approximation element က named type တွေကို ဘာကြောင့် လက်ခံလဲ ရှင်းပြနိုင်ဖို့
  • Stack[T] လို generic type တစ်ခု ဆောက်ပြီး var zero T နဲ့ zero value ပြန်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Generic function ဆိုတာ type အတွက် နေရာလွတ် (placeholder) ချန်ထားတဲ့ function ပါ။ Sum[T Number] မှာ T က "ဒီနေရာမှာ number type တစ်ခုခု လာမယ်" လို့ ပြောတာပါ။ []int နဲ့ ခေါ်ရင် T က int ဖြစ်ပြီး []float64 နဲ့ ခေါ်ရင် T က float64 ဖြစ်ပါတယ် — code ကို type တစ်ခုချင်းစီအတွက် ကူးရေးစရာ မလိုတော့ပါဘူး။

ဒါပေမယ့် T က ဘာမဆို ဖြစ်လို့ မရပါဘူး။ + နဲ့ ပေါင်းချင်ရင် T က ပေါင်းလို့ရတဲ့ type ဖြစ်ကြောင်း compiler ကို ကတိပေးရပါတယ်။ အဲဒီ ကတိကို constraint လို့ ခေါ်ပြီး Number interface က "int, int64, float64 ဒါမှမဟုတ် အဲဒါတွေကို အခြေခံထားတဲ့ type တွေပဲ" လို့ ကန့်သတ်ပေးတာပါ။

Problem → Why → Solution

ပြဿနာ: type တစ်ခုစီအတွက် function တစ်ခု

Shop app တစ်ခုမှာ ပစ္စည်းအရေအတွက် ([]int) ကိုရော ဈေးနှုန်း ([]float64) ကိုပါ ပေါင်းဖို့ လိုပါတယ်။ Generic မသုံးရင် SumInts နဲ့ SumFloats ဆိုပြီး body တူတဲ့ function နှစ်ခု ရေးရပါတယ်။ []any နဲ့ တစ်ခုတည်း ရေးကြည့်ရင်တော့ ပိုဆိုးပါတယ် — value တစ်ခုချင်းကို type assertion လုပ်ရပြီး string တစ်ခု မှားထည့်မိရင် runtime ကျမှ သိပါတယ်။

sums.go
func SumInts(xs []int) int {
    total := 0
    for _, x := range xs { total += x }
    return total
}

func SumFloats(xs []float64) float64 { // same body, copied
    total := 0.0
    for _, x := range xs { total += x }
    return total
}

func SumAny(xs []any) float64 { // compiles, but checks types at runtime
    total := 0.0
    for _, x := range xs { total += x.(float64) } // panics on an int or string
    return total
}

ဘာကြောင့် ဒီနည်းတွေ မကောင်းတာလဲ

Copy ကူးထားတဲ့ function တွေမှာ bug တစ်ခု ပြင်ရင် နေရာတိုင်းမှာ လိုက်ပြင်ရပြီး တစ်နေရာ မေ့သွားလေ့ ရှိပါတယ်။ any ကတော့ type checking ကို compile time ကနေ runtime ကို ရွှေ့လိုက်တာမို့ x.(float64) က int တစ်ခု တွေ့တာနဲ့ panic ဖြစ်ပါတယ်။ Type parameter က logic ကို တစ်ကြိမ်ပဲ ရေးခွင့်ပေးပြီး type checking ကိုလည်း compile time မှာ ထိန်းထားပေးပါတယ်။

Core concept: constraint က T ပေါ်မှာ လုပ်ခွင့်ရှိတာကို သတ်မှတ်တယ်

Generics (Go 1.18 ကစ ပါလာတာ) မှာ function နာမည်နောက်က [T Constraint] ကို type parameter list လို့ ခေါ်ပါတယ်။ Sum([]int{2, 4, 6}) လို ခေါ်ရင် compiler က argument ကနေ T = int လို့ infer လုပ်ပေးလို့ Sum[int](...) လို့ ရေးစရာ မလိုပါဘူး။ Return type မှာပဲ T ပါပြီး argument ကနေ ခန့်မှန်းလို့ မရတဲ့အခါမှ type argument ကို ကိုယ်တိုင် ရေးရပါတယ်။

Constraint ဆိုတာ interface တစ်ခုပါ၊ ဒါပေမယ့် method စာရင်းအပြင် type set ကိုလည်း ဖော်ပြနိုင်ပါတယ်။ Generic function body ထဲမှာ constraint ရဲ့ type set ထဲက type အားလုံး ထောက်ပံ့တဲ့ operation တွေကိုပဲ သုံးခွင့်ရှိပါတယ်။ any ဆိုရင် assign, pass, return လောက်ပဲ လုပ်လို့ရပြီး == တောင် မရပါဘူး။ comparable က == နဲ့ != ကို ခွင့်ပြုလို့ map key ဒါမှမဟုတ် ရှာဖွေတဲ့ function တွေအတွက် သုံးပါတယ်။ Standard library ရဲ့ cmp.Ordered (Go 1.21 ကစ) က < > <= >= ကို ခွင့်ပြုပြီး integer, float, string type တွေ အကုန် ပါပါတယ်။

ကိုယ်ပိုင် constraint ရေးတဲ့အခါ | နဲ့ type တွေ ဆက်ပါတယ်၊ ~ ကတော့ အရေးကြီးပါတယ်။ int ဆိုရင် int အတိအကျကိုပဲ ဆိုလိုပြီး ~int ဆိုရင် underlying type က int ဖြစ်တဲ့ type အားလုံး — type Kyat int, type Score int လို named type တွေပါ — ပါဝင်ပါတယ်။ Real code မှာ named type တွေ အများကြီး သုံးလို့ ~ မပါရင် "Kyat does not satisfy Number" error ကို မကြာခဏ တွေ့ရပါမယ်။

Type parameter တွေကို type တွေမှာလည်း သုံးလို့ရပါတယ် — type Stack[T any] struct { items []T } လိုပါ။ အသုံးပြုတဲ့အခါ Stack[string] လို type argument ပေးရပြီး method တွေမှာ receiver ကို (s *Stack[T]) လို့ ရေးပါတယ်။ Method တစ်ခုချင်းစီမှာတော့ ကိုယ်ပိုင် type parameter အသစ် ထပ်ထည့်ခွင့် မရှိပါဘူး။ T ရဲ့ zero value လိုရင် var zero T လို့ ကြေညာပါ — int ဆို 0၊ string ဆို ""၊ pointer ဆို nil ရပါတယ်။

Constraintခွင့်ပြုတဲ့ operationသုံးလေ့ရှိတဲ့ နေရာ
anyAssign, pass, return (== မရ)Container, Map/Filter
comparable== နဲ့ !=Map key, Contains, Index
cmp.Ordered< > <= >= နဲ့ ==Max, Min, sorting
~int | ~float64+ - * / လို arithmeticSum, Average
Mental model: constraint က ခွင့်ပြုချက် စာရင်း
  1. [T C] နဲ့ type နေရာလွတ် ချန်
  2. C က T ဖြစ်နိုင်တဲ့ type တွေ သတ်မှတ်
  3. Body က အကုန်ထောက်ပံ့တဲ့ op ပဲ သုံး
  4. ခေါ်ရင် argument ကနေ T ကို infer

Operator တစ်ခု သုံးလို့ မရဘူးဆိုရင် body ကို မပြင်ခင် constraint ကို အရင် စစ်ပါ။

အထွေထွေ ပုံစံ

go
type ConstraintName interface { ~TypeA | ~TypeB }

func FuncName[T ConstraintName](param []T) T { ... }

func Other[K comparable, V any](m map[K]V) []K { ... }

type Box[T any] struct { value T }

func (b *Box[T]) Get() T { return b.value }

Type parameter list ကို square bracket [...] ထဲမှာ ရေးပြီး parameter တစ်ခုချင်းစီမှာ constraint ပါရပါတယ်။ Type parameter အများကြီး ([K comparable, V any]) ထားလို့ ရပြီး generic type ရဲ့ method receiver မှာ [T] ကို ပြန်ရေးရပါတယ်။

Example: Number constraint နဲ့ Sum

ဒီ example မှာ ကိုယ်ပိုင် Number constraint တစ်ခု ကြေညာပြီး Sum ကို type သုံးမျိုးနဲ့ သူတို့အပေါ် အခြေခံတဲ့ named type တွေအတွက် တစ်ကြိမ်တည်း ရေးထားပါတယ်။ main() က []int နဲ့ ခေါ်ထားလို့ T က int ဖြစ်ပါတယ်။

go
package main

import "fmt"

type Number interface { ~int | ~int64 | ~float64 }

func Sum[T Number](values []T) T {
    var total T
    for _, value := range values { total += value }
    return total
}

func main() { fmt.Println(Sum([]int{2, 4, 6})) }

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Constrainttype Number interface { ~int | ~int64 | ~float64 }

    Method မပါဘဲ type set ပဲ ပါတဲ့ interface ပါ။ ~ ကြောင့် type Kyat int လို named type တွေလည်း ပါဝင်ပါတယ်။ ဒီလို type set interface ကို constraint နေရာမှာပဲ သုံးလို့ရပြီး ပုံမှန် variable type အဖြစ် မသုံးနိုင်ပါဘူး။

  2. Signaturefunc Sum[T Number](values []T) T {

    T ကို Number နဲ့ ကန့်သတ်ပြီး input slice ရော return value ပါ T ဖြစ်ပါတယ်။ []int ပို့ရင် int ပြန်ရလို့ caller ဘက်မှာ type assertion မလိုပါဘူး။

  3. Zero valuevar total T

    T ရဲ့ zero value နဲ့ စပါတယ် — int ဆို 0၊ float64 ဆို 0.0 ပါ။ Empty slice ပို့ရင် ဒီ zero value ကိုပဲ ပြန်ရပါတယ်။

  4. Loopfor _, value := range values { total += value }

    Number ထဲက type အားလုံး + ကို ထောက်ပံ့လို့ += ကို compiler က လက်ခံပါတယ်။ Constraint ကို any လို့ ပြောင်းလိုက်ရင် ဒီလိုင်းမှာ error တက်ပါမယ်။

  5. Callfunc main() { fmt.Println(Sum([]int{2, 4, 6})) }

    T = int ကို argument ကနေ infer လုပ်ပြီး 2 + 4 + 6 = 12 ကို print ထုတ်ပါတယ်။

You should see
12

comparable နဲ့ cmp.Ordered

Max က > ကို သုံးလို့ cmp.Ordered လိုပြီး Index က == ပဲ သုံးလို့ comparable လောက်နဲ့ လုံလောက်ပါတယ်။ Constraint ကို လိုတာထက် မတင်းကျပ်အောင် ရွေးတာက function ကို type ပိုများများနဲ့ သုံးနိုင်စေပါတယ် — ဥပမာ struct တွေက comparable ဖြစ်နိုင်ပေမယ့် ordered မဖြစ်ပါဘူး။ Max[float64](3, 2.5) လို type argument ကို ကိုယ်တိုင် ပေးလည်း ရပါတယ်၊ ဒါမှ 3 ကို float64 အဖြစ် ယူပါတယ်။

ordered.go
package main

import (
    "cmp"
    "fmt"
)

// Max works for any ordered type: ints, floats, strings...
func Max[T cmp.Ordered](a, b T) T {
    if a > b {
        return a
    }
    return b
}

// Index only needs ==, so the constraint is comparable.
func Index[T comparable](items []T, target T) int {
    for i, item := range items {
        if item == target {
            return i
        }
    }
    return -1
}

func main() {
    fmt.Println(Max(3, 7), Max(2.5, 1.5), Max("apple", "banana"))
    fmt.Println(Max[float64](3, 2.5)) // explicit type argument

    cities := []string{"Yangon", "Mandalay", "Bago"}
    fmt.Println(Index(cities, "Bago"), Index(cities, "Taunggyi"))
}

Output က "7 2.5 banana"၊ "3" နဲ့ "2 -1" ပါ။ String တွေကို အက္ခရာစဉ်အတိုင်း နှိုင်းယှဉ်လို့ "banana" က ပိုကြီးပါတယ်။

~ ပါမှ named type တွေ ဝင်လို့ရတယ်

Strict constraint က int | float64 အတိအကျ ဖြစ်ပြီး Loose က ~int | ~float64 ပါ။ type Kyat int ရဲ့ slice ကို SumLoose က လက်ခံပေမယ့် SumStrict ဆီ ပို့ရင် compiler က "Kyat does not satisfy Strict (possibly missing ~ for int in Strict)" လို့ ~ ပျောက်နေတာကိုတောင် အကြံပြုပေးပါတယ်။

tilde.go
package main

import "fmt"

type Strict interface{ int | float64 }
type Loose interface{ ~int | ~float64 }

func SumStrict[T Strict](xs []T) T {
    var total T
    for _, x := range xs {
        total += x
    }
    return total
}

func SumLoose[T Loose](xs []T) T {
    var total T
    for _, x := range xs {
        total += x
    }
    return total
}

type Kyat int // underlying type is int

func main() {
    prices := []Kyat{1500, 2500, 800}
    fmt.Println(SumLoose(prices))          // 4800
    fmt.Println(SumStrict([]int{1, 2, 3})) // 6
    // SumStrict(prices) does not compile:
    // Kyat does not satisfy Strict (possibly missing ~ for int in Strict)
}

Generic type: Stack[T]

Stack[T] က item တွေကို T slice ထဲမှာ သိမ်းပါတယ်။ Pop() က stack ဗလာဖြစ်ရင် ပြန်ပေးစရာ T မရှိလို့ var zero T နဲ့ zero value ကို false နဲ့အတူ ပြန်ပေးပါတယ် — map lookup ရဲ့ comma-ok ပုံစံနဲ့ တူပါတယ်။ Stack[string] နဲ့ Stack[int] က compile time မှာ type မတူတဲ့ သီးခြား type နှစ်ခုပါ။

stack.go
package main

import "fmt"

type Stack[T any] struct {
    items []T
}

func (s *Stack[T]) Push(v T) {
    s.items = append(s.items, v)
}

func (s *Stack[T]) Pop() (T, bool) {
    var zero T
    if len(s.items) == 0 {
        return zero, false
    }
    last := s.items[len(s.items)-1]
    s.items = s.items[:len(s.items)-1]
    return last, true
}

func main() {
    var pages Stack[string]
    pages.Push("home")
    pages.Push("cart")
    for i := 0; i < 3; i++ {
        p, ok := pages.Pop()
        fmt.Printf("%q %v\n", p, ok)
    }
}

Output က "cart" true၊ "home" true၊ နောက်ဆုံးမှာ "" false ပါ — နောက်ဆုံး ထည့်တာ အရင်ထွက်ပါတယ်။

လက်တွေ့ project တွေမှာ

Real project တွေမှာ ဘယ်လို သုံးလဲ

Generic code ကို ကိုယ်တိုင် မရေးခင် standard library ထဲမှာ အရင် ရှာပါ။ slices package (Go 1.21 ကစ) မှာ slices.Contains, slices.Index, slices.Sort, slices.Max တို့ ပါပြီး maps package မှာ maps.Keys လို function တွေ ပါပါတယ်။ ဒီ package တွေကို ဖွင့်ကြည့်ရင် comparable နဲ့ cmp.Ordered ကို ဒီသင်ခန်းစာထဲကအတိုင်း သုံးထားတာ တွေ့ရပါမယ်။

Application code မှာ generics အသုံးဝင်ဆုံး နေရာတွေက data structure တွေ (cache, set, queue, LRU)၊ type-safe helper တွေ (Map, Filter, GroupBy) နဲ့ repository layer မှာ Repository[T] လို ပုံစံ တူတဲ့ CRUD code ပါ။ ဒါပေမယ့် behavior မတူတဲ့ type တွေကို ကိုင်တွယ်ရင်တော့ interface က ပိုသင့်တော်ပါတယ် — generic function ထဲမှာ T ရဲ့ type ကို switch လုပ်နေရပြီဆိုရင် အဲဒါ interface သုံးသင့်တဲ့ လက္ခဏာပါ။ Go community ရဲ့ အကြံက code ကို ပုံစံတူ နှစ်ခါ သုံးခါ ကူးရေးပြီးမှ generic ပြောင်းဖို့ပါ၊ မလိုသေးခင် ကြိုမလုပ်ပါနဲ့။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. any constraint နဲ့ operator သုံးတာ

func Biggest[T any](a, b T) T { if a > b ... } က "invalid operation: a > b (type parameter T cannot use operator >)" error ပေးပါတယ်။ any က T ပေါ်မှာ operator ဘာမှ ကတိမပေးလို့ပါ။ Constraint ကို cmp.Ordered ပြောင်းပါ၊ == ပဲလိုရင် comparable သုံးပါ။

2. Constraint မှာ ~ မေ့တာ

interface{ int | float64 } လို ရေးထားရင် type Score int ရဲ့ slice ကို ပို့တဲ့အခါ "Score does not satisfy" error ရပါတယ်။ Domain type တွေ (Kyat, Score, UserID) ကို လက်ခံစေချင်ရင် ~int | ~float64 လို ~ ထည့်ပါ။

3. Interface ပိုသင့်တဲ့နေရာမှာ generic သုံးတာ

func Render[T any](v T) ထဲမှာ switch any(v).(type) နဲ့ type တစ်ခုချင်းစီကို ခွဲလုပ်နေရင် generic ရဲ့ အကျိုး မရပါဘူး။ Type တစ်ခုချင်းစီရဲ့ behavior ကွာတယ်ဆိုရင် Render() method ပါတဲ့ interface ကို သုံးပါ။ Generic က "logic တူ၊ type ပဲကွာ" တဲ့အခါအတွက်ပါ။

4. Method မှာ type parameter အသစ် ထည့်ဖို့ ကြိုးစားတာ

func (s *Stack[T]) Map[U any](f func(T) U) လို ရေးရင် compile error ဖြစ်ပါတယ် — method တွေမှာ ကိုယ်ပိုင် type parameter မရှိနိုင်ပါဘူး။ func MapStack[T, U any](s *Stack[T], f func(T) U) လို ပုံမှန် generic function အဖြစ် ရေးပါ။

Mini challenge

Mini challenge: generic helper သုံးခု

Constraint မတူတဲ့ generic function သုံးခု ရေးပြီး named type Score နဲ့ string slice နှစ်မျိုးလုံးမှာ စမ်းပါ။

  • Filter[T any](items []T, keep func(T) bool) []T — keep က true ပြန်တဲ့ item တွေပဲ ချန်ရမယ်
  • MaxOf[T cmp.Ordered](items []T) (T, bool) — empty slice ဆိုရင် zero value နဲ့ false
  • Count[T comparable](items []T, target T) int
  • type Score int ရဲ့ slice နဲ့ []string နှစ်မျိုးလုံးနဲ့ ခေါ်ပြရမယ်
helpers.go
package main

import (
    "cmp"
    "fmt"
)

// TODO: Filter — which constraint is enough when you only call keep(item)?

// TODO: MaxOf — handle the empty slice before reading items[0]
func MaxOf[T cmp.Ordered](items []T) (T, bool) {
    // TODO
}

// TODO: Count — needs ==

type Score int

func main() {
    scores := []Score{72, 95, 48, 95, 60}
    // TODO: passed (>= 60), best score, MaxOf on an empty []string,
    // how many 95s, how many "go" in []string{"go", "rust", "go"}
    fmt.Println(scores)
}

ရလဒ်: Program က ဒီလို print ထုတ်ရပါမယ်: passed: [72 95 95 60] best: 95 true empty has max: false count of 95: 2 count of go: 2

အရိပ်အမြွက် ကြည့်ရန်

Filter က keep(item) ကိုပဲ ခေါ်လို့ any နဲ့ လုံလောက်ပါတယ်။ MaxOf မှာ var best T ကို အရင် ကြေညာပြီး len(items) == 0 ဆိုရင် best, false ကို ပြန်ပါ။ Count(scores, 95) မှာ 95 က untyped constant ဖြစ်လို့ Score အဖြစ် အလိုအလျောက် ပြောင်းပါတယ်။

အဖြေ ကြည့်ရန်
helpers.go
package main

import (
    "cmp"
    "fmt"
)

func Filter[T any](items []T, keep func(T) bool) []T {
    var out []T
    for _, item := range items {
        if keep(item) {
            out = append(out, item)
        }
    }
    return out
}

func MaxOf[T cmp.Ordered](items []T) (T, bool) {
    var best T
    if len(items) == 0 {
        return best, false
    }
    best = items[0]
    for _, item := range items[1:] {
        if item > best {
            best = item
        }
    }
    return best, true
}

func Count[T comparable](items []T, target T) int {
    n := 0
    for _, item := range items {
        if item == target {
            n++
        }
    }
    return n
}

type Score int

func main() {
    scores := []Score{72, 95, 48, 95, 60}
    passed := Filter(scores, func(s Score) bool { return s >= 60 })
    fmt.Println("passed:", passed)

    best, ok := MaxOf(scores)
    fmt.Println("best:", best, ok)

    _, ok = MaxOf([]string{})
    fmt.Println("empty has max:", ok)

    fmt.Println("count of 95:", Count(scores, 95))
    fmt.Println("count of go:", Count([]string{"go", "rust", "go"}, "go"))
}

Quick Quiz 1 / 3

Body ထဲမှာ v == x ကိုပဲ နှိုင်းယှဉ်တဲ့ func Contains[T ___](items []T, x T) bool မှာ ___ နေရာအတွက် ဘယ် constraint က အသင့်တော်ဆုံးလဲ။

Quick Quiz 2 / 3

type Meters float64 ဖြစ်ပြီး Number က interface{ int | float64 } ဆိုရင် Sum([]Meters{1.5, 2}) မှာ ဘာဖြစ်မလဲ။

Quick Quiz 3 / 3

Generic type Box[T any] မှာ ဘယ် declaration က compile error ဖြစ်မလဲ။

မှတ်ထားရမယ့် အချက်များ

  • [T Constraint] က type နေရာလွတ်ပါ၊ ခေါ်တဲ့အခါ argument ကနေ T ကို အများအားဖြင့် infer လုပ်ပေးပါတယ်။
  • Constraint က body ထဲမှာ T ပေါ် သုံးခွင့်ရှိတဲ့ operation ကို ဆုံးဖြတ်ပါတယ်: any (operator မရ), comparable (==), cmp.Ordered (< >)။
  • ~int က underlying type int ဖြစ်တဲ့ named type အားလုံးကို လက်ခံပြီး int ကတော့ int အတိအကျပဲ ဖြစ်ပါတယ်။
  • Stack[T] လို generic type တွေ ဆောက်လို့ ရပေမယ့် method တွေမှာ type parameter အသစ် မထည့်နိုင်ပါဘူး။
  • Logic တူပြီး type ပဲကွာရင် generic၊ behavior ကွာရင် interface ကို ရွေးပါ။

Getting started with generics — Go

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Generics & Type Constraints | Thuta Learning