Thuta Learning
ရှာဖွေရန်
IntermediateProgrammingbeginner

Interfaces

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

Interface သည် method behavior ကိုသတ်မှတ်တဲ့ contract ပါ။ Go မှာ interface ကို explicit implements လို့ရေးစရာမလိုပါ။ Type တစ်ခုက interface ထဲက methods အားလုံးရှိနေပြီဆိုရင် အလိုအလျောက် satisfy ဖြစ်ပါတယ်။

go
package main

import "fmt"

type Notifier interface {
    Notify(message string)
}

type EmailNotifier struct{}

func (EmailNotifier) Notify(message string) {
    fmt.Println("Email:", message)
}

func sendAlert(n Notifier) {
    n.Notify("Server is running")
}

func main() {
    email := EmailNotifier{}
    sendAlert(email)
}

EmailNotifier မှာ Notify method ရှိတဲ့အတွက် Notifier interface ကို satisfy လုပ်ပါတယ်။ ဒါကြောင့် sendAlert က EmailNotifier ကိုလက်ခံနိုင်တာပါ။

You should see
Email: Server is running

Info

Interface ကိုသုံးရင် function တစ်ခုက concrete type တစ်မျိုးတည်းမဟုတ်ဘဲ behavior တူတဲ့ type မျိုးစုံနဲ့အလုပ်လုပ်နိုင်ပါတယ်။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Interface ထဲက method signature နဲ့ တိတိကျကျမကိုက်ရင် satisfy မဖြစ်ပါ။ Parameter type, return type, method name အကုန်တူရပါမယ်။
Interfaces | Thuta Learning