Top 100 Go (Golang) Interview Questions and Answers
Q1: What is Go? basics
Go is an open-source statically typed compiled language designed by Google for simplicity, efficiency, and concurrency.
Q2: What are Go modules? modules
Go modules are the dependency management system introduced in Go 1.11. A module is a collection of related Go packages with a go.mod file.
Q3: What is the difference between GOPATH and Go modules? modules
GOPATH is the old workspace model; Go modules allow arbitrary directory layout and explicit versioned dependencies using go.mod.
Q4: How do you declare a variable in Go? syntax
Use var name type or short form name := value. Example: var x int = 5; y := 10.
Q5: What are slices in Go? collections
Slices are dynamically sized, flexible views into arrays. They have length and capacity and are reference types.
Q6: Explain maps in Go. collections
Maps are unordered key-value stores. Declared with make(map[keyType]valueType) and accessed using map[key].
Q7: What is a goroutine? concurrency
A goroutine is a lightweight thread managed by Go runtime, created with the go keyword.
Q8: What are channels? concurrency
Channels allow goroutines to communicate and synchronize by sending and receiving values of a specified type.
Q9: What is select statement? concurrency
Select lets you wait on multiple channel operations; it blocks until one is ready.
Q10: How do you handle errors in Go? errors
Go uses explicit error returns (value, error). Check error != nil and handle accordingly.
Q11: What is defer? controlflow
defer schedules a function call to run after the enclosing function returns, commonly for cleanup (e.g., file.Close()).
Q12: Explain panic and recover. errors
panic stops normal flow and unwinds stack. recover can capture panic inside deferred function and resume execution.
Q13: What are interfaces in Go? types
Interfaces are sets of method signatures that types implement implicitly, promoting polymorphism.
Q14: What does it mean that Go has duck typing? types
Go uses structural typing: if a type has required methods, it satisfies an interface without explicit declaration.
Q15: What is embedding in Go? composition
Embedding includes one struct or type within another, giving promoted methods and fields for composition.
Q16: How many bytes in int, int8, int16 etc? types
int8=1, int16=2, int32=4, int64=8. int and uint are platform-dependent (32 or 64 bit).
Q17: What is the zero value? types
Zero value is the default value when a variable is declared without initialization (0 for numbers, "" for string, nil for pointers, maps, slices, channels, func, interface).
Q18: How to clone a slice? collections
Use copy: dst:=make([]T,len(src)); copy(dst,src);
Q19: How do you append to a slice? collections
Use append: s = append(s, value1, value2...).
Q20: What is nil in Go? types
nil is zero value for pointers, slices, maps, channels, interfaces and function types. It means no value/reference.
Q21: What are pointers in Go? pointers
Pointers hold memory addresses. Use & to take address and * to dereference.
Q22: What is a struct? types
Struct is a composite data type grouping fields. Example: type User struct {Name string; Age int}.
Q23: How does Go handle concurrency safety for maps? concurrency
Maps are not safe for concurrent write. Use sync.Mutex, sync.RWMutex, or sync.Map for concurrency protection.
Q24: What is sync.WaitGroup? concurrency
WaitGroup waits for a collection of goroutines to finish. Use Add/Done/Wait.
Q25: What is sync.Mutex? concurrency
Mutex provides mutual exclusion locking for critical sections to avoid race conditions.
Q26: What is sync.RWMutex? concurrency
RWMutex allows multiple readers or one writer at a time for better read performance with fewer writes.
Q27: What are goroutine leaks and how to avoid? concurrency
A goroutine leak happens when a goroutine is blocked forever. Use cancelation via context, close channels, and ensure select with done channel.
Q28: What is context.Context? concurrency
Context carries deadlines, cancellation signals, and request-scoped values across API boundaries.
Q29: What is the Go toolchain command to run tests? testing
go test ./... runs tests in all packages; go test
Q30: How to write a table-driven test? testing
Create a slice of test cases and loop over it with t.Run for each case.
Q31: What is benchmark testing? testing
Use go test -bench=. and func BenchmarkX(b *testing.B) to measure code performance across runs.
Q32: What is the built-in race detector? testing
go test -race enables race detection which finds data races in concurrent code at runtime.
Q33: What is reflection in Go? advanced
Reflection (reflect package) allows inspection and manipulation of types/values at runtime, but should be used sparingly.
Q34: What is the difference between nil and empty slice? collections
nil slice has length/capacity 0 and is nil. empty slice has len/cap 0 but is non-nil (e.g. []int{}).
Q35: What is interface{} type? types
interface{} is the empty interface that accepts values of any type and is used for generic containers.
Q36: What are type assertions? types
Type assertion x.(T) extracts concrete type from interface. Use v,ok := x.(T) to avoid panic.
Q37: What is a named return value? syntax
Functions may declare return names. They act as local variables and are returned by naked return statement.
Q38: What is the difference between value and pointer receiver? methods
Value receiver gets a copy; pointer receiver can mutate original and avoid copies for large structs. Use pointer for consistency when methods modify state.
Q39: Can methods be declared on non-struct types? methods
Yes, methods may be declared on any defined type in the same package (except built-in types), including structs and custom types.
Q40: What is nil pointer dereference? errors
Dereferencing a nil pointer causes a runtime panic. Check pointer before dereference or initialize before use.
Q41: What is gofmt? tools
gofmt automatically formats Go source code to standard style. Use gofmt -w file.go or gofmt -w .
Q42: What is go vet? tools
go vet checks for suspicious constructs and potential bugs in Go code beyond compile-time errors.
Q43: What is go test? tools
go test compiles and runs tests named *_test.go using the testing package.
Q44: What is go fmt vs go imports? tools
gofmt formats code; goimports formats code and adds/removes import statements automatically.
Q45: What is a build tag? build
Build tags are comments like //go:build windows to include/exclude files per platform or condition when building.
Q46: How does Go support cross-compilation? build
Set GOOS and GOARCH environment variables then run go build (e.g., GOOS=linux GOARCH=amd64 go build).
Q47: What is vendoring in Go? modules
Vendoring copies dependencies into vendor/ directory. go mod vendor populates it and go build can use them.
Q48: What is gofmt not enforcing? style
gofmt enforces formatting but not naming conventions, algorithmic logic, or package organization.
Q49: What is the zero-value for interface? types
Zero-value of an interface is nil (both type and value nil). A non-nil interface can wrap nil pointer and not be equal to nil.
Q50: Explain pointer to nil interface issue. types
Assigning a nil pointer to interface does not make interface nil. Check value using type assertion or compare with nil carefully.
Q51: What is a type switch? types
Type switch is switch v := x.(type) { case int: ... } used to branch on dynamic type of interface value.
Q52: How do you declare a constant? syntax
Use const name type = value. Constants are compile-time and immutable.
Q53: What are iota constants? syntax
iota is a predeclared identifier used in const blocks generating successive untyped integer constants.
Q54: What is the Go memory model? concurrency
Go memory model defines synchronization must happen via channels, mutexes, or other sync primitives for goroutine visibility and ordering.
Q55: What is GC in Go? runtime
Go uses a concurrent garbage collector that reclaims unused memory automatically while minimizing pause times.
Q56: How to inspect memory usage? tools
Use runtime/pprof, go tool pprof, and runtime.ReadMemStats; also Go Tour and pprof API to profile heaps and goroutines.
Q57: What is freeze in Go? go1.21
Go freeze is a process where API compatibility is locked while new language features are introduced carefully. It refers to stability guarantee of standard library and language.
Q58: What is a package? theory
Package groups related Go source files. Each file declares package name at top. main package is an executable entry point.
Q59: How do you import packages? theory
Use import "fmt" or import ("fmt" "os"). Packages are resolved under module cache or GOPATH.
Q60: What is init() function? init
init functions run before main. Package may have multiple init functions. Primarily used for initialization tasks.
Q61: What is defer-panic-recover pattern? error-handling
Use defer with recover to handle panics gracefully and prevent crashes in a controlled place.
Q62: How does Go handle circular imports? compile
Circular imports are forbidden. Refactor code to move shared functionality into separate packages to break cycle.
Q63: What are build constraints? build
Build constraints are comments like //go:build linux that conditionally include files for OS/ARCH/etc during build.
Q64: How to create custom errors? errors
Create types implementing Error() string and return them. Use errors.New or fmt.Errorf with %w for wrapping.
Q65: What is errors.Is and errors.As? errors
errors.Is checks if an error matches a target in chain; errors.As extracts typed error from chain for type assertion.
Q66: Explain pointer arithmetic in Go. types
Go does not support pointer arithmetic directly to maintain safety; use slices and indexing instead.
Q67: What is a blank identifier `_`? syntax
The blank identifier discards values and is used to ignore return values or imports (to run init). It cannot be used later.
Q68: What is atomic package? concurrency
sync/atomic supports lock-free atomic operations on integers/pointers for concurrent state updates.
Q69: What is a race condition? concurrency
Race condition occurs when multiple goroutines access shared data concurrently and at least one write is unsynchronized, causing unpredictable behavior.
Q70: How do you avoid race conditions? concurrency
Use channels, mutexes, atomic operations, or design data so each goroutine owns its state (share by communicating, not communicating by sharing).
Q71: What is go generate? tooling
go generate runs custom generator commands declared with //go:generate comments; not run by default with go build/test.
Q72: What is garbage collection pause? runtime
GC pause is the time execution stalls for cleanup. Go's GC aims for low pause by concurrent collection and tuning GOGC.
Q73: What is GOGC? runtime
GOGC controls heap growth before garbage collection; default 100 means GC runs when heap doubles in size.
Q74: What is pprof? profiling
pprof is Go profiling tool for CPU, memory, goroutines, and block profiles via runtime/pprof and net/http/pprof handlers.
Q75: How do you start a HTTP server in Go? net
Use net/http package; http.HandleFunc("/", handler); http.ListenAndServe(":8080", nil)
Q76: What is json.Marshal and json.Unmarshal? encoding
json.Marshal converts Go values to JSON bytes; json.Unmarshal parses JSON bytes into Go values with struct tags.
Q77: What are struct tags? reflection
Struct tags are annotation strings on fields used by encoding/json and other packages to control serialization and behavior.
Q78: What is the difference between os.Exit and return from main? runtime
os.Exit terminates immediately without running deferred calls. return from main runs deferred functions before exiting.
Q79: What is a file server in net/http? web
Use http.FileServer(http.Dir("./static")) to serve static files from a directory.
Q80: What is the difference between HTTP client and server in Go? net
net/http provides http.Client for requests and http.Server for handling inbound requests via handlers.
Q81: What is a nil map behavior? collections
Reading from nil map returns zero value; writing to nil map causes panic. Initialize map with make before writes.
Q82: What is a nil channel behavior? concurrency
Sending or receiving on nil channel blocks forever, useful for disabling branches in select.
Q83: What is buffered channel? concurrency
Buffered channel has fixed capacity, send blocks only when full, receive blocks only when empty. Created with make(chan T, n).
Q84: How do you close a channel? concurrency
Use close(ch). Receivers can still drain values; sends to closed channel panic.
Q85: What is range over channel? concurrency
for v := range ch reads values until channel is closed, then loop exits.
Q86: What is closing channel advantage? concurrency
Closing signals no more values; receivers can detect closure using v,ok := <-ch.
Q87: What are functions as first-class citizens? functions
Functions can be assigned to variables, passed as arguments, and returned from other functions.
Q88: What is closure? functions
Closure is function value that references variables from outside its body, maintaining state across calls.
Q89: How to create a generic function with Go 1.18? generics
Use type parameters in square brackets: func Max[T constraints.Ordered](a,b T) T { if a>b {return a}; return b }.
Q90: Are Go interfaces generic? generics
Go 1.18 allows generic interfaces with type parameters and constraints; previous versions used non-generic interfaces.
Q91: What is a type parameter constraint? generics
Constraint limits types used in generics using interfaces specifying required methods or comparable operator.
Q92: What is a generic slice function example? generics
func Filter[T any](s []T, fn func(T) bool) []T { for _, v := range s { if fn(v) {out = append(out,v)}} return out }
Q93: What is a nil map in a generic function? generics
You can pass nil maps to functions; reads return zero value, writes panic unless map is initialized.
Q94: What is a `go fmt` rule for `if` conditions? style
gofmt enforces braces and spacing: if cond { ... }, no parentheses around conditions required.
Q95: What is `sync.Once`? concurrency
sync.Once ensures a function is executed only once, even with concurrent calls, useful for initialization.
Q96: What is `unsafe` package? advanced
unsafe provides low-level operations for pointer arithmetic, arbitrary memory conversions, and platform dependent behavior. Use with caution.
Q97: What is `go.sum`? modules
go.sum records cryptographic hashes of module versions for dependency verification and reproducible builds.
Q98: How do you update dependencies? modules
Use go get
Q99: What is the semantic import versioning scheme? modules
For major version V2+, module path must include /vN suffix and import path must match (e.g., github.com/user/pkg/v2).
Q100: What is the difference between `go run` and `go build`? tools
go run compiles and executes program directly (temp binary). go build compiles binary without running; leaves executable in current dir.