Skill Booster

Quick Reference for Interviews...

Top 100 Go (Golang) Interview Questions and Answers

Q1: What is Go? basics

Language Overview

Go is an open-source statically typed compiled language designed by Google for simplicity, efficiency, and concurrency.

Q2: What are Go modules? modules

Dependency Management

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

Environment

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

Variables

Use var name type or short form name := value. Example: var x int = 5; y := 10.

Q5: What are slices in Go? collections

Data structures

Slices are dynamically sized, flexible views into arrays. They have length and capacity and are reference types.

Q6: Explain maps in Go. collections

Data structures

Maps are unordered key-value stores. Declared with make(map[keyType]valueType) and accessed using map[key].

Q7: What is a goroutine? concurrency

Concurrency

A goroutine is a lightweight thread managed by Go runtime, created with the go keyword.

Q8: What are channels? concurrency

Concurrency

Channels allow goroutines to communicate and synchronize by sending and receiving values of a specified type.

Q9: What is select statement? concurrency

Concurrency

Select lets you wait on multiple channel operations; it blocks until one is ready.

Q10: How do you handle errors in Go? errors

Error handling

Go uses explicit error returns (value, error). Check error != nil and handle accordingly.

Q11: What is defer? controlflow

Resource cleanup

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/recover

panic stops normal flow and unwinds stack. recover can capture panic inside deferred function and resume execution.

Q13: What are interfaces in Go? types

Type system

Interfaces are sets of method signatures that types implement implicitly, promoting polymorphism.

Q14: What does it mean that Go has duck typing? types

Type system

Go uses structural typing: if a type has required methods, it satisfies an interface without explicit declaration.

Q15: What is embedding in Go? composition

Structs

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

Primitive 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

Initialization

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

Slices

Use copy: dst:=make([]T,len(src)); copy(dst,src);

Q19: How do you append to a slice? collections

Slices

Use append: s = append(s, value1, value2...).

Q20: What is nil in Go? types

Zero values

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

Memory

Pointers hold memory addresses. Use & to take address and * to dereference.

Q22: What is a struct? types

Data structures

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

Data races

Maps are not safe for concurrent write. Use sync.Mutex, sync.RWMutex, or sync.Map for concurrency protection.

Q24: What is sync.WaitGroup? concurrency

Goroutines

WaitGroup waits for a collection of goroutines to finish. Use Add/Done/Wait.

Q25: What is sync.Mutex? concurrency

Synchronization

Mutex provides mutual exclusion locking for critical sections to avoid race conditions.

Q26: What is sync.RWMutex? concurrency

Synchronization

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

Best practices

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

Cancellation

Context carries deadlines, cancellation signals, and request-scoped values across API boundaries.

Q29: What is the Go toolchain command to run tests? testing

Testing

go test ./... runs tests in all packages; go test runs tests for one package.

Q30: How to write a table-driven test? testing

Testing

Create a slice of test cases and loop over it with t.Run for each case.

Q31: What is benchmark testing? testing

Performance

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

Debugging

go test -race enables race detection which finds data races in concurrent code at runtime.

Q33: What is reflection in Go? advanced

Runtime

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

Slices

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

Type system

interface{} is the empty interface that accepts values of any type and is used for generic containers.

Q36: What are type assertions? types

Type conversions

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

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

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

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

Runtime

Dereferencing a nil pointer causes a runtime panic. Check pointer before dereference or initialize before use.

Q41: What is gofmt? tools

Formatting

gofmt automatically formats Go source code to standard style. Use gofmt -w file.go or gofmt -w .

Q42: What is go vet? tools

Static analysis

go vet checks for suspicious constructs and potential bugs in Go code beyond compile-time errors.

Q43: What is go test? tools

Testing

go test compiles and runs tests named *_test.go using the testing package.

Q44: What is go fmt vs go imports? tools

Formatting

gofmt formats code; goimports formats code and adds/removes import statements automatically.

Q45: What is a build tag? build

Conditional 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

Toolchain

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

Dependency management

Vendoring copies dependencies into vendor/ directory. go mod vendor populates it and go build can use them.

Q48: What is gofmt not enforcing? style

Coding style

gofmt enforces formatting but not naming conventions, algorithmic logic, or package organization.

Q49: What is the zero-value for interface? types

Interfaces

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

Common bug

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

Control flow

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

Constants

Use const name type = value. Constants are compile-time and immutable.

Q53: What are iota constants? syntax

Enums

iota is a predeclared identifier used in const blocks generating successive untyped integer constants.

Q54: What is the Go memory model? concurrency

Races

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

Garbage collection

Go uses a concurrent garbage collector that reclaims unused memory automatically while minimizing pause times.

Q56: How to inspect memory usage? tools

Profiling

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

Language law

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

Organization

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

Organization

Use import "fmt" or import ("fmt" "os"). Packages are resolved under module cache or GOPATH.

Q60: What is init() function? init

Initialization

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

Panic recovery

Use defer with recover to handle panics gracefully and prevent crashes in a controlled place.

Q62: How does Go handle circular imports? compile

Package design

Circular imports are forbidden. Refactor code to move shared functionality into separate packages to break cycle.

Q63: What are build constraints? build

Cross-platform

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

Error handling

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

Error handling

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

Language rules

Go does not support pointer arithmetic directly to maintain safety; use slices and indexing instead.

Q67: What is a blank identifier `_`? syntax

Language features

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

Low-level sync

sync/atomic supports lock-free atomic operations on integers/pointers for concurrent state updates.

Q69: What is a race condition? concurrency

Bugs

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

Best practices

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

Code generation

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

Performance

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

GC tuning

GOGC controls heap growth before garbage collection; default 100 means GC runs when heap doubles in size.

Q74: What is pprof? profiling

Performance analysis

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

Web

Use net/http package; http.HandleFunc("/", handler); http.ListenAndServe(":8080", nil)

Q76: What is json.Marshal and json.Unmarshal? encoding

Serialization

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

Metadata

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

Program exit

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

Utilities

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

Networking

net/http provides http.Client for requests and http.Server for handling inbound requests via handlers.

Q81: What is a nil map behavior? collections

Safety

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

Channels

Sending or receiving on nil channel blocks forever, useful for disabling branches in select.

Q83: What is buffered channel? concurrency

Channels

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

Channels

Use close(ch). Receivers can still drain values; sends to closed channel panic.

Q85: What is range over channel? concurrency

Channels

for v := range ch reads values until channel is closed, then loop exits.

Q86: What is closing channel advantage? concurrency

Signals

Closing signals no more values; receivers can detect closure using v,ok := <-ch.

Q87: What are functions as first-class citizens? functions

Advanced

Functions can be assigned to variables, passed as arguments, and returned from other functions.

Q88: What is closure? functions

Advanced

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

Modern features

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

Modern features

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

Modern features

Constraint limits types used in generics using interfaces specifying required methods or comparable operator.

Q92: What is a generic slice function example? generics

Modern features

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

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

Formatting

gofmt enforces braces and spacing: if cond { ... }, no parentheses around conditions required.

Q95: What is `sync.Once`? concurrency

Synchronization

sync.Once ensures a function is executed only once, even with concurrent calls, useful for initialization.

Q96: What is `unsafe` package? advanced

Low-level

unsafe provides low-level operations for pointer arithmetic, arbitrary memory conversions, and platform dependent behavior. Use with caution.

Q97: What is `go.sum`? modules

Dependency security

go.sum records cryptographic hashes of module versions for dependency verification and reproducible builds.

Q98: How do you update dependencies? modules

Modules

Use go get @version or go get -u ./... for updating module dependencies.

Q99: What is the semantic import versioning scheme? modules

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

Tooling

go run compiles and executes program directly (temp binary). go build compiles binary without running; leaves executable in current dir.