Q26Go Concurrency
How do you prevent goroutine leaks?
Give each goroutine a clear lifetime and an exit path.
Answer
Propagate cancellation.
Ensure blocked channel operations can unblock.
Join work when lifecycle requires it.
Syntax
select { case item := <-items: process(item); case <-ctx.Done(): return }
Key Points
- Cancellation and completion matter
Q27Go Concurrency
How is context used for cancellation and deadlines?
Pass context as the first parameter to operations that may block and always call derived cancel functions.
Answer
Context carries cancellation and deadlines.
Do not store request contexts in structs.
Use request-scoped values sparingly.
Syntax
ctx, cancel := context.WithTimeout(parent, 2*time.Second)
defer cancel()
Key Points
- Always cancel derived contexts
Q28Go Concurrency
When use a mutex rather than a channel?
A mutex is often simplest for protecting shared in-memory state; channels suit communication and work transfer.
Answer
Keep critical sections small.
Never copy a mutex after use.
Both approaches can be correct if ownership is clear.
Syntax
type Counter struct { mu sync.Mutex; n int }
func (c *Counter) Inc(){ c.mu.Lock(); defer c.mu.Unlock(); c.n++ }
Key Points
- Protect shared invariants
Q29Go Concurrency
What is a data race and how can it be detected?
A data race is concurrent access to the same memory with at least one write and no synchronization.
Answer
Run go test -race ./....
Protect writes with mutexes, channels, or atomics.
Race-free code may still have logical concurrency bugs.
Syntax
go test -race ./...
Q30Go Concurrency
How does sync.Once work?
sync.Once runs a function exactly once across concurrent callers.
Answer
Useful for lazy initialization.
Callers wait until the initialization function completes.
Package initialization may be simpler for static values.
Syntax
var once sync.Once
var client *http.Client
func getClient() *http.Client { once.Do(func(){ client = &http.Client{} }); return client }
Key Points
- Safe one-time initialization
Q31Go Concurrency
How do atomics differ from mutexes?
Atomics synchronize operations on individual values; mutexes more naturally protect multi-field invariants.
Answer
Use typed atomics where available.
Atomics do not protect related fields as a group.
Prefer clarity over low-level cleverness.
Syntax
var requests atomic.Int64
requests.Add(1)
current := requests.Load()
Key Points
- Use the right synchronization scope
Q32Go Concurrency
How would you implement a worker pool?
A fixed number of workers read jobs from a channel, limiting concurrent work.
Answer
Bound concurrency and resource use.
The job-channel owner closes it.
Production pools need cancellation and error propagation.
Syntax
jobs := make(chan int)
var wg sync.WaitGroup
for w:=0; w<4; w++ { wg.Add(1); go func(){ defer wg.Done(); for j:=range jobs { process(j) } }() }
for _, j := range input { jobs <- j }; close(jobs); wg.Wait()
Key Points
- Bound work and join workers
Q33Go Concurrency
What is backpressure?
Backpressure limits accepted work when downstream processing is slower than incoming demand.
Answer
Use bounded queues.
Expose queue depth and rejection metrics.
Choose an explicit overload policy.
Syntax
select { case queue <- task: default: reject(task) }
Key Points
- Avoid unbounded memory growth
Q34Go Concurrency
Who should close a channel?
Usually the sender that owns the channel closes it after all sends finish.
Answer
Sending on a closed channel panics.
Closing twice panics.
Use context cancellation for many-sender shutdown patterns.
Syntax
func produce(out chan<- int) { defer close(out); for i:=0; i<5; i++ { out <- i } }
Key Points
- Make channel ownership explicit
Q35Go Services
How do you build a basic HTTP server?
Use net/http handlers and an explicitly configured Server with appropriate timeouts.
Answer
Use request contexts for downstream calls.
Configure read-header and idle timeouts.
Separate health and readiness checks.
Syntax
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request){ w.WriteHeader(http.StatusOK); _, _ = w.Write([]byte("ok")) })
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5*time.Second}
Key Points
- Configure server timeouts
Q36Go Services
How should a handler validate input and return JSON?
Decode, validate, return appropriate status codes, and encode a consistent response format.
Answer
Limit public request body sizes.
Separate syntax validation from business validation.
Do not expose internal errors.
Syntax
type CreateRequest struct { Name string `json:"name"` }
var req CreateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w,"invalid JSON",400); return }
w.Header().Set("Content-Type","application/json")
_ = json.NewEncoder(w).Encode(req)
Q37Go Services
How does HTTP middleware work?
Middleware wraps an http.Handler to add logging, authentication, metrics, or other cross-cutting behavior.
Answer
Order affects behavior.
Avoid logging secrets.
Wrap ResponseWriter if status and byte counts are needed.
Syntax
func logging(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request){ start:=time.Now(); next.ServeHTTP(w,r); log.Println(r.Method,r.URL.Path,time.Since(start)) }) }
Key Points
- Compose middleware deliberately
Q38Go Services
How do you gracefully shut down a service?
Stop accepting new requests, allow in-flight work to finish within a deadline, and stop background workers.
Answer
Handle SIGTERM in containers.
Use Server.Shutdown for graceful HTTP shutdown.
Close dependent resources in an orderly sequence.
Syntax
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop(); <-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second); defer cancel()
_ = srv.Shutdown(shutdownCtx)
Key Points
- Plan shutdown as a lifecycle
Q39Go Services
How should configuration and secrets be managed?
Load configuration from environment or files, validate it at startup, and use a secret manager for credentials.
Answer
Fail fast on invalid configuration.
Never commit secrets.
Support rotation and least privilege.
Syntax
port := os.Getenv("PORT")
if port == "" { port = "8080" }
Key Points
- Separate configuration from secrets
Q40Go Services
How do you safely call an upstream HTTP service?
Reuse a configured client, use request contexts, inspect status codes, and close response bodies.
Answer
Set timeouts.
Reuse clients and transports.
Retry only safe operations within a total deadline.
Syntax
client := &http.Client{Timeout: 3*time.Second}
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
resp, err := client.Do(req); if err != nil { return err }; defer resp.Body.Close()
Key Points
- Check status codes and close bodies
Q41Go Services
What is structured logging?
Structured logging stores fields as machine-readable key-value data.
Answer
Use consistent fields and correlation IDs.
Do not log secrets or sensitive payloads.
Use logs alongside metrics and traces.
Syntax
logger := slog.New(slog.NewJSONHandler(os.Stdout,nil))
logger.Info("request completed", "method", r.Method, "path", r.URL.Path)
Key Points
- Machine-readable diagnostics
Q42Go Testing
How do you test HTTP handlers?
Use httptest to invoke handlers without a real network listener.
Answer
Assert status, headers, and body.
Cover invalid and boundary inputs.
Inject dependencies to keep tests deterministic.
Syntax
req := httptest.NewRequest(http.MethodGet,"/health",nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec,req)
if rec.Code != 200 { t.Fatalf("got %d",rec.Code) }
Key Points
- Test behavior at boundaries
Q43Go Modules
How do Go modules and packages work?
A module is a versioned collection of packages described by go.mod.
Answer
Commit go.mod and usually go.sum.
Use stable import paths.
Avoid cyclic package dependencies.
Syntax
go mod init example.com/catalog
go get example.com/dependency
go mod tidy
Key Points
- Keep dependencies reproducible
Q44Go Architecture
How does interface-based dependency injection help?
Define small interfaces at consumer boundaries and pass implementations through constructors.
Answer
Avoid global dependencies.
Use fakes for deterministic unit tests.
Do not create abstractions without a clear benefit.
Syntax
type Store interface { Get(context.Context,string)(Item,error) }
type Service struct { store Store }
func NewService(s Store) *Service { return &Service{store:s} }
Key Points
- Inject dependencies explicitly
Q45Go Reliability
How should retries and timeouts be designed?
Use a total deadline, bounded retries, exponential backoff with jitter, and retry only transient failures when safe.
Answer
Retries can amplify outages.
Use idempotency for retried writes.
Respect upstream retry guidance where relevant.
Syntax
for attempt:=0; attempt<3; attempt++ { err:=call(ctx); if err==nil { break }; if !retryable(err) { return err }; if sleepErr:=sleepWithContext(ctx, backoff(attempt)); sleepErr!=nil { return sleepErr } }
Q46Rust Ownership
What does moving a value mean?
Assignment or passing can transfer ownership of a non-Copy value, invalidating the old binding.
Answer
Move is not necessarily a byte copy.
Copy types remain usable after assignment.
Borrow when ownership transfer is unnecessary.
Syntax
let first = String::from("hello");
let second = first;
println!("{second}");
Q47Rust Ownership
Copy versus Clone?
Copy is implicit for eligible simple types; Clone is explicit and may allocate or duplicate resources.
Answer
A type implementing Drop cannot implement Copy.
Cloning String or Vec can allocate.
Avoid expensive clones unless needed.
Syntax
let x = 7; let y = x;
let a = String::from("hi"); let b = a.clone();
Q48Rust Ownership
What are lifetimes?
Lifetimes describe relationships between references and allow the compiler to check that borrowed data outlives its use.
Answer
Annotations describe relationships, not runtime durations.
Many lifetimes are inferred.
References cannot outlive their referents.
Syntax
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str { if a.len() >= b.len() { a } else { b } }
Key Points
- Lifetimes are compile-time relationships
Q49Rust Ownership
What is a dangling reference?
A dangling reference points to invalid data; safe Rust rejects common ways to create one.
Answer
Return owned data rather than a reference to a local.
The referent must outlive every borrow.
Unsafe code requires extra invariants.
Syntax
fn valid() -> String { String::from("owned return") }
Key Points
- Do not return references to locals
Q50Rust Types
What are Option and Result?
Option models presence or absence; Result models success or failure.
Answer
Handle variants with match or combinators.
Avoid unwrap on untrusted runtime input.
The ? operator propagates compatible errors.
Syntax
fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> { s.parse() }
let name: Option<&str> = Some("Kai");
Q51Rust Types
How does pattern matching work?
match exhaustively handles enum variants and patterns; if let is convenient for one pattern.
Answer
Matches must be exhaustive.
Patterns can destructure structs and enums.
Use a catch-all only when it is semantically correct.
Syntax
match result { Ok(v) => println!("{v}"), Err(e) => eprintln!("{e}") }
Q52Rust Types
What are traits?
Traits define shared behavior that types implement; generic bounds require behavior from type parameters.
Answer
Traits provide behavior contracts.
Generics often use static dispatch.
Trait objects enable dynamic dispatch.
Syntax
trait Summarize { fn summary(&self) -> String; }
struct Article { title: String }
impl Summarize for Article { fn summary(&self)->String { self.title.clone() } }
Key Points
- Traits define shared behavior
Q53Rust Types
Generics versus trait objects?
Generics typically use monomorphized static dispatch; dyn Trait uses dynamic dispatch.
Answer
Generics can optimize well but increase code size.
Trait objects help store heterogeneous implementations.
Trait object methods must satisfy object-safety requirements.
Syntax
fn show<T: std::fmt::Display>(v:T) { println!("{v}") }
fn show_dyn(v: &dyn std::fmt::Display) { println!("{v}") }
Key Points
- Choose static or dynamic dispatch intentionally
Q54Rust Memory Safety
What is interior mutability?
Interior-mutability types allow mutation through shared references using runtime or synchronization checks.
Answer
RefCell checks borrow rules at runtime.
Mutex supports synchronized shared mutation.
Borrow conflicts in RefCell can panic.
Syntax
use std::cell::RefCell;
let value = RefCell::new(1);
*value.borrow_mut() += 1;
Key Points
- Choose thread-safe types across threads
Q55Rust Memory Safety
Compare Box, Rc, and Arc.
Box owns heap data, Rc shares ownership on one thread, and Arc shares ownership with thread-safe reference counting.
Answer
Rc is not thread-safe.
Arc does not automatically make inner mutation safe.
Arc<Mutex<T>> supports synchronized shared mutation.
Syntax
let boxed = Box::new(5);
let shared = std::rc::Rc::new(String::from("shared"));
let threaded = std::sync::Arc::new(String::from("shared"));
Key Points
- Smart pointers encode ownership patterns
Q56Rust Concurrency
What do Send and Sync mean?
Send means ownership can move across threads; Sync means shared references can safely be used across threads.
Answer
Types implement these traits based on their contents.
Rc is not Send or Sync.
Unsafe trait implementations require rigorous justification.
Syntax
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
assert_send::<String>(); assert_sync::<i32>();
Key Points
- Compile-time thread-safety contracts
Q57Rust Concurrency
How do threads communicate in Rust?
Threads can use message-passing channels or shared state protected by synchronization primitives.
Answer
Moving a sender transfers ownership.
Handle send and receive errors.
Async services often use runtime-provided channels.
Syntax
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || tx.send(42).unwrap());
let value = rx.recv().unwrap();
Key Points
- Message passing transfers values
Q58Rust Concurrency
How do you protect shared mutable state?
Use Arc<Mutex<T>> or Arc<RwLock<T>> when multiple threads need synchronized access.
Answer
Keep lock scopes short.
Define a policy for poisoned locks.
Avoid holding standard locks across async suspension points.
Syntax
let state = std::sync::Arc::new(std::sync::Mutex::new(0));
let s = state.clone();
std::thread::spawn(move || { *s.lock().unwrap() += 1; });
Key Points
- Synchronization makes sharing explicit
Q59Rust Tooling
What is Cargo used for?
Cargo manages Rust builds, dependencies, tests, formatting, and linting.
Answer
Run fmt, clippy, and tests in CI.
Audit dependencies and keep builds reproducible.
cargo check catches many errors quickly.
Syntax
cargo check
cargo fmt --check
cargo clippy -- -D warnings
cargo test
Key Points
- Use consistent tooling in CI