Practical Go Practice Questions & Quiz

40 questions / 10 random questions

slices interfaces errors context goroutines and channels HTTP databases testing modules performance and security
Try a 10-question Practical Go quiz

Random questions, instant feedback, and review for missed questions.

Start quiz →

Included topics (40 questions)

Q1

Code assumed a slice always kept the same backing array after append. What is the correct understanding?

Answer: append may allocate a new backing array when capacity is insufficient

A slice is a view with pointer, length, and capacity. Always retain append's return value because it may reference a newly allocated array.

Q2

How should code distinguish an absent map key from a stored zero value?

Answer: Use value, ok := m[key]

The comma-ok idiom reports key presence. A missing key still yields the element type's zero value, so the value alone is insufficient.

Q3

An external package type should satisfy a local interface. What is required in Go?

Answer: It satisfies the interface implicitly by having the required method set

Interface implementation is implicit. A consumer can define a minimal interface, and any type with the matching method set satisfies it.

Q4

A method must modify a struct's state. Which receiver is appropriate?

Answer: A pointer receiver

A pointer receiver can mutate the original value and avoid copying a large struct. Keep receiver choices consistent across the type's methods.

Q5

You need to add operation context while preserving sentinel-error checks. What is appropriate?

Answer: Wrap with fmt.Errorf("load user: %w", err) and use errors.Is

Using %w preserves the error chain, allowing added context while callers inspect causes with errors.Is or errors.As.

Q6

A function has multiple early returns after opening a file. How should it avoid leaking the file?

Answer: Defer file.Close() immediately after a successful open

Registering defer immediately after acquisition closes the resource on later return paths. Handle close errors explicitly when they matter.

Q7

A library panics on ordinary input-validation failure. What is the preferred API improvement?

Answer: Return expected failures as errors

Panic is for unrecoverable invariant violations. Invalid input and external I/O failures should be returned as errors callers can handle.

Q8

An outbound API call must follow request cancellation and deadlines. What design is appropriate?

Answer: Pass the caller's context.Context as the first argument and attach it to the request

Propagate context through the call chain into HTTP and database operations. The creator of a cancel function should defer its call.

Q9

When a pipeline consumer exits early, producer goroutines block forever on channel sends. What should be improved?

Answer: Select between sending and context Done, propagating cancellation to all stages

Each stage should observe cancellation and be able to leave blocked sends or receives, preventing goroutine leaks.

Q10

Who should normally close a job channel shared by multiple workers?

Answer: The sending owner that knows all sends are complete

The sending owner that knows all sends are finished should close the channel. Receiver-side closure can cause concurrent senders to panic.

Q11

When does a send on an unbuffered channel complete?

Answer: When a corresponding receiver is ready to receive the value

An unbuffered channel creates a rendezvous: send and receive block until both sides are ready, combining communication with synchronization.

Q12

A select with default caused a loop to consume a full CPU core. What explains and improves it?

Answer: default runs without waiting, so introduce blocking or a timer

When no case is ready, default runs immediately and can busy-loop. Remove default when waiting is intended or use an appropriate timer.

Q13

Many jobs need concurrency without creating one goroutine per input and exhausting memory. What is appropriate?

Answer: A bounded worker pool with a fixed number of workers reading a job channel

Bound concurrency with worker count and design queueing and backpressure. Add context cancellation, error collection, and completion waiting.

Q14

Multiple goroutines read and write the same map. How should it be protected?

Answer: Confine ownership to one goroutine or synchronize with a mutex

Concurrent reads and writes on a regular map are unsafe. Choose ownership confinement, a mutex, or sync.Map when its specialized use case fits.

Q15

Which command should CI use to detect data races in exercised code?

Answer: go test -race ./...

The race detector instruments executed memory accesses. Run it with tests and integration workloads that exercise concurrent paths.

Q16

You need to close a results channel only after several goroutines finish. What is appropriate?

Answer: Track completion with sync.WaitGroup and close after Wait

Call Add before launch, defer Done in each worker, and have one coordinator close after Wait to prevent double close and send-after-close.

Q17

Expensive client initialization may be requested concurrently but must run once. What should be used?

Answer: sync.Once

sync.Once.Do executes a function once even under concurrent calls and synchronizes visibility of initialization results.

Q18

Several fields must be updated as one consistent state. Is a single atomic counter sufficient?

Answer: Use a mutex or publish immutable snapshots for compound invariants

Atomics work for individual values but do not automatically preserve invariants across fields. Synchronize a critical section or publish whole snapshots.

Q19

An outbound HTTP API can hang and accumulate goroutines. What is the baseline improvement?

Answer: Reuse an http.Client with appropriate client or transport timeouts and propagate context

Reuse clients and transports and set connection, header, and overall deadlines. Close response bodies and bound retries with backoff.

Q20

When an inbound HTTP request disconnects, a downstream database query should stop. What is appropriate?

Answer: Pass r.Context() to QueryContext

An http.Request context is canceled on client disconnect or request completion. Passing it to context-aware APIs stops unnecessary downstream work.

Q21

Which baseline configuration helps protect a public HTTP server from slow clients such as Slowloris?

Answer: Configure http.Server timeouts such as ReadHeaderTimeout for the workload

Tune ReadHeaderTimeout, ReadTimeout, WriteTimeout, and IdleTimeout to traffic characteristics and align them with reverse-proxy limits.

Q22

How should a Go HTTP server shut down safely when Kubernetes sends a termination signal?

Answer: Receive a signal context and call Server.Shutdown with a bounded context

Stop accepting new work, allow in-flight requests a bounded grace period, and define forced termination after the deadline; fail readiness first.

Q23

A JSON API must separate Go field names from wire names and omit empty values. What should be used?

Answer: Add a json:"user_id,omitempty" tag to an exported field

encoding/json processes exported fields, with struct tags controlling wire names and omitempty. Understand each type's empty-value semantics.

Q24

Configuration JSON typos must fail as unknown fields instead of being silently ignored. What is appropriate?

Answer: Enable json.Decoder.DisallowUnknownFields

For strict configuration loading, use DisallowUnknownFields and separately validate required values and ranges after decoding.

Q25

How should database/sql execute a query containing user input safely?

Answer: Use placeholders and bound arguments

Bind values using the driver's placeholder syntax and allowlist dynamic identifiers. String concatenation creates SQL injection risk.

Q26

Several SQL updates must run in a transaction and reliably roll back on errors. What is the usual pattern?

Answer: Defer Rollback after BeginTx and Commit only on success

A deferred tx.Rollback covers early returns and is harmless after a successful commit. Use tx methods throughout the transaction.

Q27

A multi-gigabyte upload must be processed without loading it all into memory. Which abstraction fits?

Answer: Stream from io.Reader, using io.Copy where appropriate

io.Reader and Writer enable chunked streaming. Also enforce size limits and handle cancellation and partial-write errors.

Q28

bufio.Scanner stopped on an unusually long line. What should be done?

Answer: Set Scanner.Buffer limits or use bufio.Reader as required, and check Err

Scanner has a token-size limit. Set a justified bound rather than making untrusted input unlimited, and handle Err after scanning.

Q29

Many input and expected-output cases must test one function readably. What is appropriate?

Answer: Use a table-driven test with named t.Run subtests

A table of names, inputs, and expectations makes cases easy to add and failures easy to locate. Watch shared state when parallelizing.

Q30

How should an HTTP handler be unit-tested without opening a real port?

Answer: Use httptest.NewRequest and httptest.NewRecorder

httptest request and recorder call handlers directly and verify status, headers, and body. Use httptest.Server for client integration.

Q31

You need to compare execution time and allocations before and after an optimization. What is appropriate?

Answer: Use testing.B benchmarks with -benchmem

Go benchmarks adapt iteration counts and report time and allocations per operation. Run repeatedly in a stable environment and compare statistically.

Q32

You want unexpected parser inputs to reveal crashes or invariant violations. What should be used?

Answer: Define a Go fuzz test with seed corpus and invariants

Fuzzing mutates seed inputs and minimizes and stores crashing cases. It is useful for parsers at security boundaries.

Q33

Which command reconciles go.mod and go.sum after imports change?

Answer: go mod tidy

go mod tidy adds required module requirements and checksums and removes unnecessary ones. CI can verify that it leaves no diff.

Q34

What is the primary role of go.sum?

Answer: Record checksums of downloaded module content for verification

go.sum records hashes for module versions and go.mod content, helping detect tampering or mismatches. It is normally committed.

Q35

A package should be importable only from within its repository subtree. What should be used?

Answer: Place it under an internal directory

The Go toolchain enforces import visibility for internal directories, avoiding accidental public API commitments.

Q36

A go.work file supports local development across modules. What should CI be careful about?

Answer: Ensure CI does not accidentally test only a local workspace combination; control GOWORK and test modules independently

go.work is useful but may make CI select local modules instead of released dependency versions. Verify each module independently.

Q37

Which Go-specific tool checks whether known dependency vulnerabilities are reachable from your code?

Answer: govulncheck ./...

govulncheck combines the Go vulnerability database with call-graph analysis to report known vulnerabilities affecting reachable code.

Q38

You need to investigate CPU hotspots and allocation sources under production-like load. What is appropriate?

Answer: Capture profiles with runtime/pprof or net/http/pprof and analyze with go tool pprof

Capture CPU, heap, and goroutine profiles over representative windows and inspect top entries or flame graphs. Restrict profiling endpoints.

Q39

Logs in a distributed system must be searchable and correlate requests. What is an appropriate Go service logging design?

Answer: Use slog or similar structured fields for level, message, request ID, operation, and error

Structured logging enables field-based filtering and aggregation. Propagate trace or request IDs and redact credentials and personal data.

Q40

Which combination appropriately ships a small Go service container and handles termination signals?

Answer: Build with a multi-stage image, use a minimal runtime image, and handle shutdown with signal.NotifyContext

Separate the build toolchain from runtime, include only required CA or timezone data, and perform bounded graceful shutdown from a signal context.

certdrill.dev is an independent, unofficial learning site and is not affiliated with LPI Japan, IPA, AWS, Microsoft Azure, or any exam provider. Questions and explanations are original content.