LearningTech

🚀

Go Advanced

In-depth concepts and advanced techniques

26. Slice vs Array â–¼

Array: Fixed length, value type (copying copies entire array).

Slice: Dynamic length, reference type (pointer to underlying array).

27. Preventing concurrent map writes â–¼

Maps are not safe for concurrent use. Use sync.Mutex to lock before access, or use sync.Map for specific high-concurrency read-heavy cases.

28. Embedding vs Inheritance â–¼

Go favors Composition. Embedding a struct allows utilizing its methods, but it's not "is-a" relationship, it's "has-a" with syntax sugar.

type Car struct { Engine } // Car promotes methods of Engine
29. go mod & module management â–¼

go mod init creates a new module. go.mod tracks dependencies and versions, replacing the old GOPATH system.

30. Use of defer â–¼

Schedules a function call to be run after the surrounding function returns. Executed in LIFO order. Common for cleanup (closing files, unlocking mutexes).

31. Panic vs Recover â–¼

Panic: Stops normal execution, unwinds stack, runs deferred functions. Used for unrecoverable errors.

Recover: Regains control of a panicking goroutine. Only works inside defer.

32. Memory Alignment â–¼

The CPU reads data in word-sized chunks. Go struct fields are aligned to these boundaries. Proper ordering of struct fields (largest to smallest) can save memory by reducing padding.

33. Context Package â–¼

Used to carry deadlines, cancellation signals, and request-scoped values across API boundaries and between processes.

34. Escape analysis impact â–¼

Determines if variables should be on stack or heap. Heap allocation causes GC pressure. Optimization: Keep variables on stack (don't return pointers to local vars if not needed) to reduce GC overhead.

35. Rate-limited HTTP client â–¼

Use golang.org/x/time/rate.Limiter or a Token Bucket implementation. Call Wait(ctx) before making a request.