🐹

Go (Golang) MCQ

Test your Go (Golang) knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.

100 Questions 40 Beginner 40 Intermediate 20 Advanced

How This Practice Test Works

Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 40 beginner questions to confirm your fundamentals, work through the 40 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.

Curated by Tech Baithak Editorial Team  ·  Last updated: June 2026

1

Which company created the Go programming language?

B

Correct Answer

Google

Explanation

Go was designed by Robert Griesemer, Rob Pike, and Ken Thompson at Google and released in 2009.

2

What is the file extension for Go source files?

C

Correct Answer

.go

Explanation

Go source files use the .go extension.

3

How do you declare a variable with type inference in Go?

B

Correct Answer

x := 5

Explanation

The short variable declaration x := 5 infers the type. var x int = 5 is the explicit form. := cannot be used at package level.

4

What is the zero value of an int in Go?

D

Correct Answer

0

Explanation

In Go, every type has a zero value. int/float = 0, bool = false, string = "", pointer/slice/map/channel/function = nil.

5

What is a goroutine?

B

Correct Answer

A lightweight, independently-executing function managed by the Go runtime

Explanation

go f() launches f as a goroutine. Goroutines are multiplexed onto OS threads by the Go scheduler and are extremely cheap (2-8KB initial stack).

6

What is a channel in Go?

B

Correct Answer

A typed conduit for safe communication between goroutines

Explanation

ch := make(chan int) creates an unbuffered channel. Send with ch <- val and receive with val := <-ch. Channels synchronize goroutines.

7

What does the defer keyword do?

B

Correct Answer

Schedules a function call to run when the surrounding function returns

Explanation

defer f.Close() ensures f.Close() is called when the function exits. Deferred calls run in LIFO order.

8

What is a slice in Go?

B

Correct Answer

A dynamically-sized, flexible view into an underlying array

Explanation

A slice ([]T) has a pointer, length, and capacity. make([]int, 5) or []int{1,2,3}. append() grows it automatically.

9

What is a map in Go?

B

Correct Answer

A hash table providing key-value associations

Explanation

map[string]int{"a": 1} is a map literal. make(map[string]int) initializes an empty map. Access with m["key"]; delete with delete(m, "key").

10

What is an interface in Go?

B

Correct Answer

A type defining a set of method signatures; any type implementing all methods implicitly satisfies the interface

Explanation

type Writer interface { Write([]byte) (int, error) } — any type with a Write method satisfies Writer without explicit declaration.

11

What is the blank identifier _ used for?

B

Correct Answer

Discarding a value when it is not needed

Explanation

_, err := f() discards the first return value. The blank identifier prevents "declared and not used" compile errors.

12

What does Go's multiple return values feature allow?

B

Correct Answer

A function returning more than one value, commonly used for (result, error) pairs

Explanation

func divide(a, b float64) (float64, error) returns both a result and an error, avoiding exceptions.

13

How do you handle errors in Go idiomatically?

B

Correct Answer

Checking the returned error value and handling it explicitly

Explanation

result, err := doSomething(); if err != nil { return err } is the idiomatic Go error handling pattern.

14

What is the empty interface interface{} (or any) in Go?

B

Correct Answer

An interface satisfied by every type, used to hold any value

Explanation

interface{} (aliased as any in Go 1.18) can hold any value. Use type assertions or type switches to retrieve the underlying value.

15

What is a struct in Go?

B

Correct Answer

A composite value type grouping named fields

Explanation

type Point struct { X, Y int } defines a struct. Structs are value types in Go; assignment copies the entire struct.

16

How do you add a method to a struct?

B

Correct Answer

Define a function with a receiver: func (p *Point) Scale(n int)

Explanation

func (p Point) String() string { ... } or func (p *Point) Scale(n int) { p.X *= n } define methods. Pointer receivers allow mutation.

17

What is a pointer receiver vs value receiver?

B

Correct Answer

Pointer receiver (*T) allows mutation and avoids copying; value receiver (T) gets a copy and cannot modify the original

Explanation

Use *T receivers to modify the struct or avoid copying. Use T receivers when you only need read access and the struct is small.

18

What does make() do in Go?

B

Correct Answer

Initializes and returns slices, maps, and channels

Explanation

make([]int, 5, 10) creates a slice with length 5, capacity 10. make(map[string]int) initializes a map. make(chan int, 10) creates a buffered channel.

19

What does new() do in Go?

B

Correct Answer

Allocates memory for a type and returns a pointer to its zero value

Explanation

p := new(int) allocates an int zeroed to 0 and returns *int. For structs, prefer &MyStruct{} which can also initialize fields.

20

What is package main in Go?

B

Correct Answer

The special package name for executables; must contain main()

Explanation

Only programs (not libraries) use package main with a func main(). Libraries use any other package name.

21

What is the purpose of go.mod?

B

Correct Answer

The module definition file specifying the module path and dependency requirements

Explanation

go.mod defines the module (module example.com/myapp) and lists direct dependencies with versions.

22

What is the select statement used for?

B

Correct Answer

Choosing between multiple channel operations, blocking until one can proceed

Explanation

select { case v := <-ch1: ... case ch2 <- x: ... default: ... } allows non-blocking or multiplexed channel operations.

23

What is panic in Go?

B

Correct Answer

An unrecoverable runtime error that unwinds the stack, unless caught by recover()

Explanation

panic(msg) stops normal execution and begins unwinding. Use recover() inside a deferred function to catch panics. Don't use panic for ordinary errors.

24

What does recover() do?

B

Correct Answer

Stops a panic and returns the value passed to panic()

Explanation

recover() is only useful inside a deferred function. It stops the panic and returns the panic value, allowing the program to continue.

25

What is embedding in Go?

B

Correct Answer

Promoting a type's methods and fields into another struct by including it without a field name

Explanation

type Animal struct { ... }; type Dog struct { Animal; Name string } embeds Animal. Dog has all Animal methods directly.

26

What is the range keyword used for?

B

Correct Answer

Iterating over slices, maps, strings, channels, and arrays returning index/key and value

Explanation

for i, v := range slice { } iterates with index and value. for k, v := range myMap { } iterates map keys and values.

27

What is a variadic function in Go?

B

Correct Answer

A function accepting a variable number of arguments using ...T

Explanation

func sum(nums ...int) int accepts any number of ints. Inside, nums is []int. Call as sum(1,2,3) or sum(slice...).

28

What does the init() function do?

B

Correct Answer

Runs automatically before main() for package initialization

Explanation

init() is called automatically after all variable declarations in the package. A package can have multiple init() functions.

29

What is a type assertion in Go?

B

Correct Answer

Extracting a concrete type value from an interface: val, ok := i.(ConcreteType)

Explanation

val, ok := i.(string) safely checks if i holds a string. Without ok, a failed assertion panics.

30

What is a type switch?

B

Correct Answer

A switch statement that matches on the dynamic type of an interface value

Explanation

switch v := i.(type) { case int: ... case string: ... } matches the runtime type of i.

31

What are exported identifiers in Go?

B

Correct Answer

Identifiers starting with an uppercase letter, visible outside the package

Explanation

Go uses capitalization for visibility. Println, Error, and UserID are exported. println, myVar are unexported (package-private).

32

What is a constant in Go?

B

Correct Answer

A value declared with const that is evaluated at compile time

Explanation

const Pi = 3.14159 or const ( A = iota; B; C ) using iota for enum-like values.

33

What does iota do in a const block?

B

Correct Answer

Generates successive integer values starting from 0 within a const block

Explanation

const ( A = iota; B; C ) assigns A=0, B=1, C=2. iota resets to 0 in each const block.

34

What is the for range idiom for channels?

B

Correct Answer

Receives from a channel until it is closed

Explanation

for v := range ch { } reads from ch until close(ch) is called. Without close, the loop blocks forever.

35

How do you check if a key exists in a map?

B

Correct Answer

val, ok := m["key"]; if ok { }

Explanation

The two-value map access val, ok := m[key] sets ok to false (and val to zero value) if key is absent.

36

What is composition over inheritance in Go?

B

Correct Answer

Building complex types by embedding simpler structs and interfaces rather than using class inheritance

Explanation

Go has no class inheritance. Functionality is composed by embedding structs and satisfying interfaces, which encourages smaller, focused types.

37

What does append() return?

B

Correct Answer

A new slice with the appended elements (must be reassigned)

Explanation

s = append(s, 1, 2, 3) returns a potentially new slice (if reallocation occurred). Always use the return value.

38

What is the purpose of sync.WaitGroup?

B

Correct Answer

Waits for a collection of goroutines to finish using Add, Done, and Wait

Explanation

wg.Add(1); go func() { defer wg.Done(); }(); wg.Wait() blocks until all added goroutines call Done.

39

What is a rune in Go?

B

Correct Answer

An alias for int32, representing a Unicode code point

Explanation

A rune is an alias for int32, holding a single Unicode code point. for _, r := range "Go" iterates runes, not bytes.

40

What does context.Context provide?

B

Correct Answer

Cancellation, deadline, and request-scoped values propagated across API boundaries and goroutines

Explanation

context.WithCancel, WithDeadline, WithTimeout create contexts. Pass ctx as the first argument to functions to propagate cancellation.

1

What is the Go scheduler?

B

Correct Answer

The M:N scheduler (goroutines:OS threads) that multiplexes goroutines onto CPU cores using a work-stealing algorithm

Explanation

Go's runtime scheduler (GOMAXPROCS=CPU cores by default) uses M:N threading: M goroutines on N OS threads, with work-stealing across P (processor) queues.

2

What is the difference between buffered and unbuffered channels?

B

Correct Answer

Unbuffered channels synchronize sender and receiver; buffered channels allow sending up to capacity without a matching receiver

Explanation

make(chan int) is unbuffered — send blocks until received. make(chan int, 5) buffers up to 5 values; send only blocks when buffer is full.

3

What is the errors.Is() function?

B

Correct Answer

Checks if an error matches a target error by unwrapping the error chain

Explanation

errors.Is(err, ErrNotFound) unwraps the error chain to check if any error matches ErrNotFound. Use errors.As() to extract a specific error type.

4

What is a sync.Mutex used for?

B

Correct Answer

Providing mutual exclusion to protect shared data from concurrent access

Explanation

mu.Lock(); /* critical section */ mu.Unlock() prevents concurrent goroutines from accessing shared state simultaneously. Use defer mu.Unlock() for safety.

5

What is a sync.RWMutex?

B

Correct Answer

A mutex that allows multiple concurrent readers but only one writer

Explanation

RLock()/RUnlock() for read-only access; Lock()/Unlock() for writes. Many goroutines can RLock simultaneously; Lock waits for all readers to finish.

6

What is an error wrapping in Go 1.13+?

B

Correct Answer

Adding context to an error with %w in fmt.Errorf, preserving the original error for errors.Is/As inspection

Explanation

fmt.Errorf("parsing: %w", err) wraps err. errors.Is(wrappedErr, io.EOF) traverses the chain.

7

What is sync.Once used for?

B

Correct Answer

Executing a function exactly once even when called from multiple goroutines, useful for lazy initialization

Explanation

var once sync.Once; once.Do(func() { /* init */ }) runs the function at most once, safely from any number of goroutines.

8

What is a sync.Pool?

B

Correct Answer

A thread-safe cache of reusable objects to reduce GC pressure

Explanation

sync.Pool stores temporary objects. Get() retrieves a pooled object; Put() returns it. The GC may collect pooled objects at any time.

9

What is the Go garbage collector's concurrency model?

B

Correct Answer

A tri-color mark-sweep GC that runs mostly concurrently with the program, with very short stop-the-world pauses

Explanation

Go's GC targets <1ms STW pauses. It marks objects concurrently with the program. The write barrier maintains invariants during concurrent marking.

10

What is the difference between a nil slice and an empty slice?

B

Correct Answer

A nil slice has no backing array (len=0, cap=0, nil); an empty slice ([]int{}) has a backing array with zero elements

Explanation

var s []int is nil (s == nil is true). s := []int{} or make([]int, 0) is empty (s == nil is false). Both have length 0 and can be appended to.

11

What does GOMAXPROCS control?

B

Correct Answer

The number of OS threads that can execute Go code simultaneously (defaults to number of CPUs)

Explanation

runtime.GOMAXPROCS(n) sets the number of P (processors) in the scheduler. Default is runtime.NumCPU(), enabling true parallelism.

12

What is a closure in Go?

B

Correct Answer

A function value that references variables from outside its body; the function may access and modify the referenced variables

Explanation

adder := func(x int) func() int { sum := 0; return func() int { sum += x; return sum } }(5) — the inner func closes over sum.

13

What is the difference between copy() and assignment for slices?

B

Correct Answer

Assignment copies the slice header (shares backing array); copy() copies elements into a pre-allocated destination

Explanation

b := a copies the slice header — both share the same backing array. copy(b, a) copies element values; b must be pre-allocated.

14

What is a goroutine leak?

B

Correct Answer

A goroutine that blocks forever because its channel is never closed or read from, preventing garbage collection

Explanation

Goroutine leaks occur when goroutines wait for channels that are never signaled. Use context cancellation or timeout to ensure goroutines can exit.

15

What is the go vet tool?

B

Correct Answer

A static analysis tool that reports suspicious constructs like misuse of sync primitives, printf format strings, and more

Explanation

go vet catches bugs that the compiler misses, such as wrong printf format verbs or copying a mutex by value.

16

What is the context package's cancellation propagation?

B

Correct Answer

Cancelling a parent context automatically cancels all derived child contexts

Explanation

ctx, cancel := context.WithCancel(parent) — calling cancel() propagates cancellation to all contexts derived from ctx.

17

What is escape analysis in Go?

B

Correct Answer

The compiler's determination of whether a variable should live on the stack or heap based on whether it escapes the function

Explanation

If a variable's address is taken and stored in a longer-lived location, it escapes to the heap. Stack allocation is cheaper (no GC pressure).

18

What is atomic operations used for in Go?

B

Correct Answer

Performing lock-free concurrent operations on integers and pointers without race conditions

Explanation

atomic.AddInt64(&counter, 1) increments counter atomically without a mutex, using CPU compare-and-swap instructions.

19

What is a goroutine's stack behavior in Go?

B

Correct Answer

Goroutines start with a small stack (typically 2-8KB) that grows and shrinks dynamically as needed

Explanation

Go uses segmented/contiguous stacks that start small and grow automatically. This makes creating thousands of goroutines practical.

20

What is the error interface in Go?

B

Correct Answer

A built-in interface with a single Error() string method

Explanation

type error interface { Error() string } — any type implementing Error() string satisfies the error interface. Create with errors.New() or fmt.Errorf().

21

What is a sentinel error in Go?

B

Correct Answer

A package-level error variable used for comparison: var ErrNotFound = errors.New("not found")

Explanation

Sentinel errors allow callers to check err == io.EOF. With error wrapping, use errors.Is(err, io.EOF) to check the chain.

22

What is the context.WithTimeout vs context.WithDeadline difference?

B

Correct Answer

WithTimeout accepts a duration from now; WithDeadline accepts an absolute time.Time

Explanation

ctx, cancel := context.WithTimeout(parent, 5*time.Second) is equivalent to context.WithDeadline(parent, time.Now().Add(5*time.Second)).

23

What does go build -race do?

B

Correct Answer

Enables the race detector that instruments the binary to detect data races at runtime

Explanation

The race detector instruments memory accesses. When two goroutines access the same memory without synchronization, it reports "DATA RACE" with a full stack trace.

24

What is a Go module proxy?

B

Correct Answer

A server caching Go module downloads, providing faster and more reliable module retrieval (GOPROXY=https://proxy.golang.org)

Explanation

GOPROXY controls where go get fetches modules. The default proxy.golang.org caches all public modules. GONOSUMDB and GOPRIVATE control private module access.

25

What is the difference between value and pointer method sets for interface satisfaction?

B

Correct Answer

A pointer *T has the method set of both value and pointer receivers; a value T only has value receiver methods — so *T satisfies more interfaces than T

Explanation

If Stringer is implemented with *T receiver, only *T satisfies Stringer, not T. You cannot take the address of an interface value to recover the original pointer.

26

What does go generate do?

B

Correct Answer

Runs commands specified in //go:generate comments to automate code generation (stringer, mockgen, etc.)

Explanation

//go:generate go run golang.org/x/tools/cmd/stringer -type=Status in source triggers stringer when running go generate. The developer must manually run go generate.

27

What is a build tag/constraint in Go?

B

Correct Answer

//go:build <expression> at the top of a file to conditionally include it based on OS, architecture, or custom tags

Explanation

//go:build linux && amd64 includes the file only when compiling for Linux on x86-64. Custom tags: //go:build integration with go test -tags integration.

28

What is the purpose of the io.Reader and io.Writer interfaces?

B

Correct Answer

Minimal interfaces enabling composable I/O: io.Reader has Read([]byte), io.Writer has Write([]byte), accepted by many standard library functions

Explanation

io.Copy(dst io.Writer, src io.Reader) works with files, buffers, network connections, and custom types — all implementing these two methods.

29

What is a functional option pattern in Go?

B

Correct Answer

Passing variadic func(T) functions to constructors, allowing flexible and extensible configuration without large config structs

Explanation

func NewServer(opts ...Option) — Option is func(*Server). WithTimeout(d) returns func(*Server) { s.timeout = d }. Popular in Go libraries like grpc-go.

30

What is the go vet tool specifically checking for with printf verbs?

B

Correct Answer

Detecting mismatches between printf format verbs and argument types, e.g., using %d for a string

Explanation

fmt.Printf("%d", "hello") is caught by go vet as a vet error. It also catches unreachable code, suspicious type assertions, and mutex copies.

31

What is the difference between make(chan T) and make(chan T, 1)?

B

Correct Answer

make(chan T) creates an unbuffered channel (synchronizes sender and receiver); make(chan T, 1) creates a channel with capacity 1 (sender doesn't block if buffer empty)

Explanation

Unbuffered: send blocks until received. Buffered with 1: send succeeds immediately if buffer empty; blocks only when full. Used for signaling without blocking.

32

What is table-driven testing in Go?

B

Correct Answer

A pattern declaring test cases as a slice of structs with inputs and expected outputs, running each case in a subtest loop

Explanation

tests := []struct{in string; want int}{{"abc",3},{"",0}}; for _, tt := range tests { t.Run(tt.in, func(t *testing.T) { ... }) }

33

What does http.Handler vs http.HandlerFunc distinguish?

B

Correct Answer

http.Handler is an interface with ServeHTTP; http.HandlerFunc is a function type that implements Handler, allowing plain functions to serve as handlers

Explanation

http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { }) converts a function to an http.Handler by implementing ServeHTTP.

34

What is the time.Ticker vs time.Timer difference?

B

Correct Answer

time.Timer fires once after a duration; time.Ticker fires repeatedly at a fixed interval until stopped

Explanation

time.NewTimer(5*time.Second) fires once. time.NewTicker(1*time.Second) fires every second. Always call Stop() to release resources.

35

What is the net/http server's concurrency model?

B

Correct Answer

Each incoming HTTP connection spawns a goroutine, so handlers run concurrently and must synchronize any shared state

Explanation

net/http automatically spawns a goroutine per connection. Handlers are called concurrently — protect shared data with mutexes or channels.

36

What is the stringer tool and its use in Go?

B

Correct Answer

A code generator (go:generate stringer) that creates String() methods for integer-based constants (iota enums)

Explanation

//go:generate stringer -type=Weekday generates func (w Weekday) String() string returning "Monday", "Tuesday", etc. Avoids hand-writing fmt.Stringer.

37

What is golang.org/x/sync/errgroup?

B

Correct Answer

A package combining WaitGroup and error collection for multiple goroutines, canceling the group context on first error

Explanation

g, ctx := errgroup.WithContext(parent); g.Go(func() error { return work(ctx) }); if err := g.Wait(); err != nil { } — first error cancels ctx.

38

What is the difference between new(T) and &T{}?

B

Correct Answer

new(T) allocates zeroed memory for any type; &T{} is struct literal syntax allowing field initialization and is idiomatic for structs

Explanation

For structs, &Point{X: 1, Y: 2} is idiomatic and allows initialization. new(Point) gives a zeroed *Point. For non-struct types (maps, slices), use make instead.

39

What is the Go workspace mode (go.work)?

B

Correct Answer

A multi-module workspace allowing local development across multiple modules without editing go.mod replace directives

Explanation

go.work (Go 1.18+) lists module paths: use ./module1 use ./module2. go build and go test in any module use local versions of listed modules.

40

What is the difference between panic and log.Fatal in Go?

B

Correct Answer

panic unwinds the stack and can be recovered; log.Fatal prints a message and calls os.Exit(1), which cannot be recovered and skips deferred functions

Explanation

Use log.Fatal in main() for unrecoverable startup errors. panic is for invariant violations. os.Exit skips deferred cleanup — prefer panic in libraries.

1

What is the Go data race detector and how do you enable it?

B

Correct Answer

A runtime tool built on ThreadSanitizer, enabled with -race flag, that detects actual concurrent memory accesses at runtime

Explanation

go test -race or go run -race instruments the binary. The race detector catches actual concurrent reads/writes, not just potential ones.

2

What is the Go memory model's guarantee about goroutine communication?

B

Correct Answer

The Go memory model defines happens-before relationships: channel sends happen before receives, sync primitives establish ordering

Explanation

The Go memory model (2022 revision) specifies that a send on a channel happens before the corresponding receive, and close happens before a receive of the zero value.

3

What is pprof and when would you use it?

A

Correct Answer

A performance profiler that samples CPU usage, memory allocations, goroutine stacks, and more

Explanation

Import net/http/pprof for HTTP endpoints. Use go tool pprof to analyze CPU profiles (find hot paths), heap profiles (memory leaks), and goroutine dumps.

4

What is generics in Go 1.18 and what are type constraints?

B

Correct Answer

Type parameters with constraints (interfaces) specifying what operations a type parameter must support

Explanation

func Min[T constraints.Ordered](a, b T) T uses a type parameter T constrained to Ordered. The compiler generates specialized code or uses GC shape stenciling.

5

What is GC shape stenciling in Go generics?

B

Correct Answer

Grouping types with the same GC shape (pointer/non-pointer) to share a single instantiation, reducing binary size

Explanation

Go 1.18 shares instantiations for types with the same underlying GC shape (e.g., all pointers share one instantiation). This differs from C++'s full specialization per type.

6

What is the difference between sync.Map and a regular map with a mutex?

B

Correct Answer

sync.Map is optimized for high-read, low-write workloads with disjoint sets of keys per goroutine; a mutex map is simpler and faster when writes are frequent

Explanation

sync.Map uses two maps internally: a read-optimized atomic map and a dirty write map. It excels at stable-keyed high-concurrency reads. mutex+map is often better for write-heavy workloads.

7

What is the unsafe package used for in Go?

B

Correct Answer

Bypassing Go's type safety for low-level operations like pointer arithmetic, struct field offsets, and converting between pointer types

Explanation

unsafe.Pointer, unsafe.Sizeof, unsafe.Offsetof are used for performance-critical code and C interop (cgo). Breaks type safety — use sparingly.

8

What is the Go linker's link-time optimization (LTO) and dead code elimination?

B

Correct Answer

The Go linker statically removes unreachable functions and packages from the binary, keeping binaries small

Explanation

Go's linker performs dead code elimination. Only reachable code from main (and init) is included. This is why Go binaries are self-contained and relatively small.

9

What is the reflect package used for in Go?

B

Correct Answer

Inspecting and manipulating types and values at runtime through reflection API

Explanation

reflect.TypeOf(x), reflect.ValueOf(x) enable inspecting types and values. Used by encoding/json, ORM libraries, and test frameworks. Avoid reflection in hot paths.

10

What is cgo and what are its performance implications?

B

Correct Answer

A mechanism to call C code from Go; crossing the Go/C boundary has overhead (goroutine stack switch, GC root reporting) and complicates builds

Explanation

cgo enables calling C libraries. Each cgo call must switch from a goroutine stack to an OS thread stack. This adds ~200ns overhead per call and disables cross-compilation.

11

What is Go's internal package mechanism?

B

Correct Answer

A directory named "internal" whose packages can only be imported by code within the parent of the internal directory

Explanation

myproject/internal/auth can only be imported by packages within myproject/. External packages get a compile-time error, enforcing package privacy without module boundaries.

12

What is the Go ABI and how did it change in Go 1.17?

B

Correct Answer

Go 1.17+ uses a register-based calling convention (ABI) passing arguments in registers rather than the stack, improving performance by ~5-10%

Explanation

Before Go 1.17, all arguments and return values were passed on the stack. The new register ABI passes integer args in RAX, RBX, RCX, RDI, RSI, R8, R9, R10, R11.

13

What is Go's sync.Map vs a map with RWMutex for read-heavy workloads?

B

Correct Answer

sync.Map excels when: same keys are read repeatedly, goroutines access disjoint keys. For high-write or small maps, mutex+map has lower overhead

Explanation

sync.Map benchmarks show benefits for stable, high-concurrency read-heavy maps. For general use, measure: sync.Map has higher overhead per operation due to interface{} boxing.

14

What is the Go compiler's inlining budget?

B

Correct Answer

A cost-based threshold (currently 80 AST nodes) controlling whether a function is inlined at call sites

Explanation

go build -gcflags=-m shows inlining decisions. Functions exceeding the budget are not inlined. go:noinline and go:yesplease override. Inlining enables further optimizations.

15

What is the difference between go test -count=1 and running tests without it?

B

Correct Answer

-count=1 disables test caching, forcing fresh execution; without it, go test caches results and skips retesting unchanged packages

Explanation

go test caches results based on code and test flags. go test -count=1 bypasses this cache, crucial for benchmarks or tests with external state.

16

What is the Go linker's dead code elimination vs tree shaking?

B

Correct Answer

Go's linker performs whole-program dead code elimination, removing unreachable functions. It does not do per-module tree shaking like JavaScript bundlers

Explanation

The Go linker starts from main and marks reachable symbols. Unreachable functions and their dependencies are excluded. This is why Go binaries include no unused code.

17

What is fuzz testing in Go 1.18+?

B

Correct Answer

A built-in fuzzing engine (go test -fuzz=FuzzXxx) that generates and mutates inputs to find cases where the function panics or fails invariants

Explanation

func FuzzReverse(f *testing.F) { f.Fuzz(func(t *testing.T, s string) { ... }) } — the fuzzer mutates s to find edge cases. Failing inputs are saved to testdata/fuzz/.

18

What is the Go compiler's escape analysis output and how do you inspect it?

B

Correct Answer

go build -gcflags=-m prints why variables escape to the heap, helping identify unintentional allocations in performance-critical code

Explanation

go build -gcflags="-m -m" shows detailed escape analysis. "moved to heap" means an allocation occurs. Closures over pointers, interface conversions often cause escape.

19

What is the impact of interfaces on Go performance (interface boxing)?

B

Correct Answer

Storing a value in an interface allocates a two-word pair (type pointer + data pointer/value); small values inline but larger ones heap-allocate (interface boxing)

Explanation

An interface value is two words: *type and *data. For small scalars, data is stored directly. For pointers and larger types, it points to heap. Avoid interfaces in hot paths.

20

What is Go's profiling tool chain for CPU and memory?

B

Correct Answer

go test -cpuprofile/memprofile generates profiles; go tool pprof analyzes them with web, top, list commands; net/http/pprof serves live profiles

Explanation

runtime.StartCPUProfile writes to a file. net/http/pprof exposes /debug/pprof/ endpoints. go tool pprof http://localhost:8080/debug/pprof/heap provides interactive analysis.