Golang / GoLang System Architecture and Testing Interview Questions
How do generics in Go 1.18+ enable better system design and what are the trade-offs?
Go generics allow writing type-safe, reusable data structures and algorithms without code duplication or losing type information through interfaces. The key use cases: generic data structures, result/option types, and typed collections.
// Generic Result type — eliminates panic-or-nil patterns
type Result[T any] struct {
value T
err error
}
func Ok[T any](v T) Result[T] { return Result[T]{value: v} }
func Err[T any](e error) Result[T] { return Result[T]{err: e} }
func (r Result[T]) Unwrap() (T, error) { return r.value, r.err }
func (r Result[T]) IsOk() bool { return r.err == nil }
// Generic ordered set
type Set[T comparable] struct {
items map[T]struct{}
}
func NewSet[T comparable]() *Set[T] {
return &Set[T]{items: make(map[T]struct{})}
}
func (s *Set[T]) Add(v T) { s.items[v] = struct{}{} }
func (s *Set[T]) Has(v T) bool { _, ok := s.items[v]; return ok }
func (s *Set[T]) Len() int { return len(s.items) }
// Generic Map/Filter/Reduce — functional pipeline without reflect
func Map[T, U any](slice []T, fn func(T) U) []U {
result := make([]U, len(slice))
for i, v := range slice { result[i] = fn(v) }
return result
}
func Filter[T any](slice []T, pred func(T) bool) []T {
var result []T
for _, v := range slice {
if pred(v) { result = append(result, v) }
}
return result
}
// Usage
users := []User{{ID: 1, Active: true}, {ID: 2, Active: false}}
activeIDs := Map(
Filter(users, func(u User) bool { return u.Active }),
func(u User) int { return u.ID },
)
// [1] — type-safe, zero reflect, zero allocation overheadTrade-offs: generics increase code readability but slightly increase compile time. The Go implementation uses GCShape monomorphisation — types with the same memory layout share one instantiation, reducing binary size compared to full C++ monomorphisation. Avoid generics for simple cases — if a plain interface satisfies the requirement, prefer it.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
