05 Deep Dive (Internals)
Chaliye engine hood khol kar dekhte hain! 🚗
1. Arrays vs Slices (Memory) 🧠
- Array: Fixed size. Agar
[5]intbanaya to size 5 hi rahega. - Slice: Dynamic window over array.
Internal Structure of Slice
Slice me 3 cheezein hoti hain:
- Pointer: Underlying array ka address.
- Length (
len): Abhi kitne elements hain. - Capacity (
cap): Total kitne aa sakte hain (resize hone se pehle).
arr := [5]int{10, 20, 30, 40, 50} // Arrayslice := arr[1:4] // Slice (20, 30, 40)
fmt.Println(len(slice)) // 3fmt.Println(cap(slice)) // 4 (Kyunki array me aage 4 elements hain)2. Interfaces (Duck Typing) 🦆
Go me “Implements” keyword nahi hota. Agar koi struct kisi Interface ke sare methods define kar de, to wo us Interface ko implement karta hai.
type Shape interface { Area() float64}
type Circle struct { radius float64 }
// Circle ne Shape implement kar liya (Autmatically!)func (c Circle) Area() float64 { return 3.14 * c.radius * c.radius}3. Maps (Dictionaries) 🗺️
Key-Value pairs store karne ke liye. (Under the hood Hash Table).
scores := make(map[string]int)scores["Aditya"] = 95scores["Rohan"] = 88
// Check if key existsval, exists := scores["Rahul"]if !exists { fmt.Println("Rahul nahi mila!")}4. Defer, Panic, Recover 🛡️
Go me try-catch nahi hota.
defer: Function khatam hone ke baad chalega (Stack order: LIFO).panic: Program crash kar do (Exception).recover: Crash rok lo (Catch).
func safeCalls() { defer func() { if r := recover(); r != nil { fmt.Println("Recovered from:", r) // Crash bacha liya } }()
panic("Oops! Kuch galat ho gaya.")}