AnyCompiler

Interfaces

Ek interface un methods ka set define karta hai jo ek type ke paas hona chahiye. Kai languages ke ulat, Go mein koi "implements" keyword bilkul nahi hai — ek type automatically 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})
}
Output
Area: 12.57

Ek real missing-method error kaisa dikhta hai

Kyunki satisfaction structurally check hoti hai, ek aisa type pass karna jisme ek required method missing hai, compile time par turant pakda jaata hai. Yeh genuinely 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})
}
Output
# 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 — fix karne ke liye koi explicit declaration nahi hai, kyunki shuru se hi koi thi hi nahi. Missing method add karo, 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 karo jiska method Name() string ho. Ek struct Dog { DogName string } define karo jiska Name() method d.DogName return kare. Ek function greet(n Named) likho jo "Hello, " + n.Name() print kare. greet ko Dog{DogName: "Rex"} ke saath call karo.