Interfaces
Ek interface un methods ka set define karta hai jo ek type ke paas hona chahiye. Kai languages ke bar-aks, Go mein koi "implements" keyword bilkul nahi hai — ek type khud ba khud ek interface ko satisfy kar deta hai, bas matching names aur signatures wale methods hone se. Ise implicit (ya structural) interface satisfaction kaha jaata hai.
package main
import "fmt"
type Shape interface {
Area() float64
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14159 * c.Radius * c.Radius
}
func describe(s Shape) {
fmt.Printf("Area: %.2f\n", s.Area())
}
func main() {
describe(Circle{Radius: 2})
}Area: 12.57
Ek real missing-method error kaisa dikhta hai
Kyunke satisfaction structurally check hoti hai, ek aisa type pass karna jisme ek required method missing hai, compile time par foran pakra jaata hai. Yeh waqai woh hai jo compiler report karta hai — ek real run se capture kiya gaya hai, plausible dikhne ke liye likha nahi gaya:
package main
import "fmt"
type Shape interface {
Area() float64
}
type Triangle struct {
Base, Height float64
}
func describe(s Shape) {
fmt.Printf("Area: %.2f\n", s.Area())
}
func main() {
describe(Triangle{Base: 4, Height: 3})
}# command-line-arguments ./main.go:18:19: cannot use Triangle literal (type Triangle) as type Shape in argument to describe: Triangle does not implement Shape (missing Area method)
Triangle ne kabhi ek Area() method define nahi kiya, isliye yeh bas Shape ko satisfy nahi karta — theek karne ke liye koi explicit declaration nahi hai, kyunke shuru se hi koi thi hi nahi. Missing method add karein, aur bilkul wahi Triangle value bina kisi aur change ke Shape ko satisfy kar degi.
Aage: pointers — & aur *, Rust ke ownership model se zyada direct.
Practice exercise
Ek interface Named define karein jiska method Name() string ho. Ek struct Dog { DogName string } define karein jiska Name() method d.DogName wapas kare. Ek function greet(n Named) likhein jo "Hello, " + n.Name() print kare. greet ko Dog{DogName: "Rex"} ke sath call karein.