Sample questions
Question 1Easy
What is context.Context mainly used for?
- Logging
- Storing global configuration that every package reads at startup instead of using flags
- Replacing channels
- Carrying cancellation, deadlines and request-scoped values across calls
Answer: D. Carrying cancellation, deadlines and request-scoped values across calls
Explanation
Functions check ctx.Done() to stop work when the caller cancels or a deadline passes.
Step-by-step solution
- Context is used to carry cancellation signals across function calls.
- It also holds deadlines for operations to time out properly.
- Request-scoped values are passed through context for efficient access.
- Functions use
ctx.Done() to detect when cancellation happens. - This helps stop ongoing work gracefully without errors.
- Final answer: Carrying cancellation, deadlines and request-scoped values across calls.
Why the other options are wrong
- A. Logging is done with the log package or a logging library; context is not for that.
- B. Global configuration is not context's job; config is read from flags, files or env.
- C. Context does not replace channels; it signals cancellation, while channels pass data.
Tip: Use context for managing cancellation and deadlines in Go programs.
Question 2Easy
By convention, which parameter position does context.Context take in Go functions?
- The first parameter, usually named ctx
- The last parameter
- Inside a struct field, so it is stored once and shared by every method of the type
- It is never passed explicitly
Answer: A. The first parameter, usually named ctx
Explanation
func Fetch(ctx context.Context, id string) is the standard form.
Step-by-step solution
- In Go, functions use context.Context to manage cancellation and deadlines.
- The context is passed as the first parameter in function signatures.
- This convention helps developers easily identify and handle context in their code.
- Functions like Fetch take context.Context as the first parameter, usually named ctx.
- So the correct position for context.Context is the first parameter.
Why the other options are wrong
- B. The last parameter is not the convention; ctx comes first, so this is not idiomatic.
- C. A context is not stored in structs by convention; it is passed explicitly to each call.
- D. Context is passed explicitly in calls; leaving it out is not the convention.
Tip: Remember: context.Context is always the first parameter in Go functions.
Question 3Easy
What does sync.Mutex provide?
- A buffered channel that queues goroutines and wakes them one by one in arrival order
- A way to start goroutines
- Mutual exclusion: one goroutine at a time in a critical section
- Atomic integer types
Answer: C. Mutual exclusion: one goroutine at a time in a critical section
Explanation
Lock and Unlock around shared data; defer mu.Unlock() is a common pattern.
Step-by-step solution
- sync.Mutex ensures only one goroutine can access shared data at a time.
- It uses Lock and Unlock methods to control access to critical sections.
- Defer mu.Unlock() is used to release the lock after use.
- This prevents race conditions by enforcing mutual exclusion.
- Final answer: Mutual exclusion: one goroutine at a time in a critical section.
Why the other options are wrong
- A. A buffered channel is not sync.Mutex; a mutex locks a section rather than queuing work.
- B. Starting goroutines is done with the go keyword, not with sync.Mutex.
- D. Atomic integer types live in sync/atomic, not in sync.Mutex.
Question 4Medium
Why might sync/atomic be preferred over a mutex for a simple counter?
- It allows non-integer values only
- It updates the value atomically without a lock, with less overhead
- It makes the counter persistent
- Mutexes cannot protect integer variables, so counters must always use the atomic package
Answer: B. It updates the value atomically without a lock, with less overhead
Explanation
atomic.AddInt64 or atomic.Int64 suits single-value updates; mutexes suit multi-step critical sections.
Step-by-step solution
- A mutex locks and unlocks around the counter.
- atomic uses a single CPU instruction.
- So it avoids lock overhead and contention.
Why the other options are wrong
- A. Atomics work on integers and pointers, not 'non-integers only'.
- C. Atomics do not persist anything.
- D. Mutexes can protect any variable.
Question 5Medium
What is the output?
package main
import (
"context"
"fmt"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
<-ctx.Done()
fmt.Println(ctx.Err())
}
- context canceled
- Deadlock: all goroutines are asleep
- <nil>
- context deadline exceeded
Answer: A. context canceled
Explanation
After cancel, Done is closed and Err returns context.Canceled, which prints as 'context canceled'.
Step-by-step solution
- cancel() closes ctx.Done()
- ctx.Err() reads the error.
- fmt.Println outputs 'context canceled'
- The program exits normally.
- Final answer: context canceled.
Why the other options are wrong
- B. No deadlock: cancel closes Done already, so the receive returns at once.
- C. Err is not nil after cancel; it holds context canceled, so <nil> is wrong here.
- D. No deadline was set, so the error is not deadline exceeded; the cancel call caused it.
Tip: Remember cancel() closes the Done channel.
Question 6Medium
What is the output?
package main
import (
"fmt"
"sync"
)
func main() {
var once sync.Once
count := 0
for i := 0; i < 3; i++ {
once.Do(func() { count++ })
}
fmt.Println(count)
}
- 1
- 3
- 0
- Compile error
Answer: A. 1
Explanation
sync.Once runs the function only on the first Do call, which is useful for lazy initialisation.
Step-by-step solution
- sync.Once ensures the function runs only once, even if called multiple times.
- The loop runs 3 times but the func inside once.Do runs only once, incrementing count by 1.
- Count starts at 0 and is incremented once, so final value is 1.
- fmt.Println prints the final value of count, which is 1.
- Final answer: 1.
Why the other options are wrong
- B. The Do call runs its function only once, so count is not incremented three times.
- C. count starts at 0 and Do runs the increment once, so 0 is wrong.
- D. No compile error: sync.Once and the closure are valid, so the program builds and runs.
Tip: Remember sync.Once executes its function only on the first call.
Question 7Medium
sync.RWMutex is useful when:
- You need to send values between goroutines
- Reads are frequent and writes rare, since readers can share the lock
- You want a lock that can be unlocked twice
- Writes greatly outnumber reads, since writers can share the lock while readers wait
Answer: B. Reads are frequent and writes rare, since readers can share the lock
Explanation
Many readers may hold RLock together; a writer's Lock is exclusive.
Step-by-step solution
- sync.RWMutex lets many readers hold the lock at the same time.
- A writer needs exclusive access, so it waits for readers to finish.
- So it helps when reads are frequent and writes are rare, which is option B.
Why the other options are wrong
- A. Sending values between goroutines is the job of channels, not a mutex.
- C. A mutex cannot be unlocked twice; unlocking an unlocked mutex is a fatal error that crashes the program and cannot be recovered.
- D. Writers do not share the lock; readers share it, so it helps when reads dominate.
Tip: RWMutex: many readers at once, one writer at a time.
Question 8Hard
Why must a sync.Mutex not be copied after first use?
- Copying a mutex is a compile error, so the program will not build until the copy is removed
- Mutexes are pointers already
- The copy duplicates its internal state, breaking mutual exclusion
- Copies are automatically shared
Answer: C. The copy duplicates its internal state, breaking mutual exclusion
Explanation
Pass structs containing mutexes by pointer; go vet's copylocks check catches this.
Step-by-step solution
- Sync.Mutex uses internal state to track locks.
- Copying it duplicates this state, leading to incorrect locking behavior.
- This breaks mutual exclusion, allowing multiple locks on the same resource.
- The copy creates a new mutex with its own state, not shared with the original.
- Final answer: The copy duplicates its internal state, breaking mutual exclusion.
Why the other options are wrong
- A. Copying a mutex is not a compile error; it builds, but the copy misbehaves at run time.
- B. Mutexes are not pointers; sync.Mutex is a struct value, so copying it copies its state.
- D. Copies are not shared automatically; a copy gets its own separate state, not the original's.
Tip: Never copy a Mutex after first use; pass by pointer instead.
Question 9Hard
A deadlock occurs when goroutine A holds lock 1 and waits for lock 2, while B holds 2 and waits for 1. A standard prevention is:
- Use
RWMutex everywhere instead of Mutex, because read-write locks cannot deadlock - Call
runtime.GC() before locking - Always acquire locks in the same global order
- Use more goroutines
Answer: C. Always acquire locks in the same global order
Explanation
Consistent lock ordering removes the circular wait.
Step-by-step solution
- Deadlock happens when two goroutines wait for each other's locks.
- Acquiring locks in a fixed global order avoids this cycle.
- Locks acquired in same order prevent circular dependency.
- This ensures no deadlock occurs between goroutines.
- Final answer: Always acquire locks in the same global order.
Why the other options are wrong
- A. RWMutex does not prevent lock-order cycles; it can still deadlock.
- B. runtime.GC does not release locks or fix lock ordering, so the cycle stays.
- D. More goroutines do not fix lock ordering; they add contention and cannot break the cycle.
Tip: Always lock in a fixed order to avoid deadlocks.
Practise all 9 questions free
The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.
Open this topic in the app →