InterviewTreedInterviewTreed

InterviewTreed Question Bank

Go & Rust Interview Questions and Answers

Prepare for Go and Rust programming, concurrency, memory management, systems development, backend services, and performance-oriented application design.

Total Questions

80

Beginner

26

Intermediate

34

Advanced

20

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Go Fundamentals

What is Go and where is it used?

Go is a compiled, statically typed language commonly used for cloud services, APIs, networking, and command-line tools.

Answer

It has garbage collection and a concise language design.

Its standard library includes HTTP, JSON, testing, and concurrency support.

It is a strong fit for network services and infrastructure tools.

Syntax

package main
import "fmt"
func main() { fmt.Println("Hello, Go") }

Key Points

  • Compiled and statically typed
  • Strong standard library
Q2Go Fundamentals

How do var, :=, and const differ?

Use var for declarations, := for short declarations inside functions, and const for constants.

Answer

The short declaration operator infers a type and is only available inside functions.

Constants represent values known at compile time.

Avoid accidental shadowing of outer variables.

Syntax

var port int = 8080
const service = "catalog"
func run() { timeout := 5; _ = timeout }

Key Points

  • Short declarations are function-scoped
  • Constants are immutable
Q3Go Fundamentals

What are common Go built-in types?

Go has bool, string, integer, floating-point, and complex types, plus aliases such as byte and rune.

Answer

byte is an alias for uint8.

rune is an alias for int32 and commonly represents a Unicode code point.

Numeric types are distinct and conversions may need to be explicit.

Syntax

var ok bool = true
var count int = 3
var label string = "ready"
var ch rune = '界'

Key Points

  • Understand zero values
  • Conversions can be explicit
Q4Go Fundamentals

How do if, for, and switch work?

Go omits required parentheses around conditions and uses for as its only loop keyword.

Answer

Braces are required around blocks.

for supports classic, condition-only, and range forms.

Switch cases do not fall through by default.

Syntax

if n > 0 { fmt.Println(n) }
for i := 0; i < 3; i++ { fmt.Println(i) }
switch status { case "ready": fmt.Println("ok"); default: fmt.Println("wait") }

Key Points

  • for is the only loop keyword
  • Switch cases do not fall through
Q5Go Functions

How do functions return multiple values?

Go functions commonly return a result and an error as separate values.

Answer

Callers should inspect errors explicitly.

Multiple return values can make outcomes clear.

Use contextual wrapping when returning an existing error.

Syntax

func divide(a, b float64) (float64, error) {
 if b == 0 { return 0, errors.New("division by zero") }; return a/b, nil
}

Key Points

  • Errors are values
  • Check errors at call sites
Q6Go Functions

What are named return values?

Named returns document result names and are initialized to their zero values.

Answer

They can be useful for small functions.

Bare returns can reduce readability in long functions.

Handle empty input explicitly.

Syntax

func bounds(v []int) (min, max int) {
 if len(v)==0 { return 0,0 }; min,max=v[0],v[0]; return
}

Key Points

  • Prefer clarity over cleverness
Q7Go Collections

What is the difference between arrays and slices?

Arrays have fixed length in their type; slices describe a variable-length view over an underlying array.

Answer

Slices are the usual collection abstraction.

append may allocate a new backing array.

Arrays are copied when assigned by value.

Syntax

fixed := [3]int{1,2,3}
items := []int{1,2,3}
items = append(items, 4)

Key Points

  • Array length is part of its type
  • Retain append result
Q8Go Collections

Explain slice length and capacity.

Length is the number of accessible elements; capacity is the available space from the slice start to the backing array end.

Answer

Capacity is not the same as length.

Slices can share a backing array.

Appending can cause reallocation.

Syntax

s := make([]int, 2, 4)
s = append(s, 30)
fmt.Println(len(s), cap(s))

Key Points

  • Aliased slices can affect one another
Q9Go Collections

How do maps work in Go?

Maps store key-value pairs and must be initialized before writes.

Answer

A nil map can be read but not written.

Map iteration order is unspecified.

The comma-ok form detects missing keys.

Syntax

scores := make(map[string]int)
scores["Asha"] = 95
value, ok := scores["Asha"]

Key Points

  • Initialize maps before writing
Q10Go Collections

How does range work?

range iterates over slices, arrays, maps, strings, and channels with type-dependent values.

Answer

For slices it yields index and value.

For maps it yields key and value, in unspecified order.

Use underscore to ignore an unused result.

Syntax

for i, v := range []string{"a", "b"} { fmt.Println(i, v) }
for k, v := range scores { fmt.Println(k, v) }

Key Points

  • Map order is unspecified
Q11Go Structs

What are structs?

Structs combine named fields into a composite type.

Answer

Keyed literals are easier to maintain.

Fields receive their type zero values when omitted.

Uppercase identifiers are exported from a package.

Syntax

type User struct { ID int; Name string }
u := User{ID: 7, Name: "Asha"}

Key Points

  • Use keyed literals for clarity
Q12Go Structs

What are methods and receivers?

A method is a function associated with a receiver type.

Answer

Pointer receivers can mutate the original value.

Value receivers operate on a copy of the receiver.

Use receiver style consistently for a type.

Syntax

type Counter struct { N int }
func (c *Counter) Inc() { c.N++ }

Key Points

  • Pointer receivers enable mutation
Q13Go Interfaces

How do interfaces work in Go?

An interface specifies methods, and a type satisfies it implicitly by implementing them.

Answer

There is no explicit implements keyword.

Small interfaces are easier to compose.

An interface value carries dynamic type and value information.

Syntax

type Writer interface { Write([]byte) (int, error) }

Key Points

  • Implicit satisfaction
  • Prefer small interfaces
Q14Go Errors

How should errors be handled?

Check returned errors and add useful context when propagating failures.

Answer

Do not ignore errors without a reason.

Use %w to wrap errors for errors.Is and errors.As.

Avoid leaking internal details to end users.

Syntax

data, err := os.ReadFile(path)
if err != nil { return fmt.Errorf("read config: %w", err) }

Key Points

  • Errors are explicit control flow
Q15Go Errors

What are defer, panic, and recover?

defer schedules cleanup at function return; panic signals an exceptional failure and recover can intercept a panic in a deferred function.

Answer

Deferred calls run last-in-first-out.

Expected failures should usually be returned as errors.

Recover is most appropriate at controlled boundaries.

Syntax

f, err := os.Open(path)
if err != nil { return err }
defer f.Close()

Key Points

  • Use defer for cleanup
Q16Go Concurrency

What is a goroutine?

A goroutine is a lightweight execution unit managed by the Go runtime.

Answer

The go keyword starts concurrent execution.

Program exit does not wait for goroutines.

Use synchronization or cancellation instead of sleep-based coordination.

Syntax

go func() { fmt.Println("work") }()

Key Points

  • Every goroutine needs a lifecycle plan
Q17Go Concurrency

What is a channel?

A channel lets goroutines exchange typed values and synchronize execution.

Answer

Unbuffered sends wait for a receiver.

Buffered channels hold a limited number of values.

Close indicates no more values will be sent.

Syntax

jobs := make(chan int)
go func() { jobs <- 42 }()
job := <-jobs

Key Points

  • Channels communicate and synchronize
Q18Go Concurrency

Buffered versus unbuffered channels?

An unbuffered channel synchronizes sender and receiver; a buffered channel can temporarily store values.

Answer

Sending to a full buffer blocks.

Receiving from an empty channel blocks.

Buffering should be an intentional backpressure decision.

Syntax

unbuffered := make(chan string)
buffered := make(chan string, 2)
buffered <- "a"

Key Points

  • Buffers do not remove blocking entirely
Q19Go Concurrency

What does select do?

select waits until one of its channel operations can proceed.

Answer

A default case makes the select non-blocking.

It is useful for timeouts and multiplexing.

If multiple cases are ready, one is selected pseudo-randomly.

Syntax

select {
case v := <-results: fmt.Println(v)
case <-time.After(time.Second): fmt.Println("timeout")
}

Key Points

  • Useful for timeouts
Q20Go Concurrency

What is sync.WaitGroup for?

WaitGroup waits for a collection of goroutines to finish.

Answer

Call Add before starting work.

Pair Add counts with Done calls.

Do not copy a WaitGroup after first use.

Syntax

var wg sync.WaitGroup
wg.Add(1)
go func(){ defer wg.Done(); work() }()
wg.Wait()

Key Points

  • WaitGroup joins goroutines
Q21Rust Fundamentals

Explain Rust ownership.

Each value has an owner; when the owner goes out of scope the value is dropped unless ownership has moved or been borrowed.

Answer

Ownership enables memory safety without a tracing garbage collector.

Moves transfer ownership for many non-Copy types.

Drop releases owned resources at scope end.

Syntax

fn main() { let message = String::from("hello"); println!("{message}"); }

Key Points

  • Every value has an owner
Q22Rust Fundamentals

What is the difference between let and mut?

Rust bindings are immutable by default; mut allows reassignment or mutation through that binding.

Answer

mut applies to the binding.

Interior mutability is provided by types such as Cell and Mutex.

Immutability by default helps make code easier to reason about.

Syntax

let label = "ready";
let mut count = 0;
count += 1;

Key Points

  • Immutable by default
Q23Rust Fundamentals

String versus &str?

String owns a growable UTF-8 buffer; &str is a borrowed string slice.

Answer

Use String when ownership or mutation is needed.

&str is a flexible read-only parameter type.

UTF-8 strings cannot be indexed by arbitrary integer offsets.

Syntax

let owned = String::from("hello");
let borrowed: &str = &owned;

Key Points

  • Owned versus borrowed data
Q24Rust Ownership

What is borrowing?

Borrowing accesses a value through a reference without taking ownership, under compile-time aliasing rules.

Answer

References do not own their referents.

Borrowing can avoid unnecessary clones.

Prefer &str over &String for many string parameters.

Syntax

fn length(text: &str) -> usize { text.len() }
let name = String::from("Ravi");
let n = length(&name);

Key Points

  • Borrow without transferring ownership
Q25Rust Ownership

Difference between &T and &mut T?

&T is an immutable reference; &mut T permits mutation and requires exclusive access during the borrow.

Answer

Multiple immutable borrows may coexist.

A mutable borrow must be exclusive.

These rules prevent many invalid-reference and data-race bugs.

Syntax

fn append_mark(s: &mut String) { s.push('!'); }
let mut text = String::from("Go");
append_mark(&mut text);

Key Points

  • Mutable borrows are exclusive
Q80Rust Fundamentals

What is the Rust ownership scope rule?

An owned local value is dropped when its owner leaves scope, unless ownership has moved elsewhere.

Answer

Scope-based drop releases resources deterministically.

Moving a value transfers the responsibility to drop it.

Borrowed references do not extend a value beyond its valid lifetime.

Syntax

{ let message = String::from("temporary"); println!("{message}"); } // dropped at block end

Key Points

  • Deterministic resource cleanup

Intermediate Questions

Implementation details, practical patterns, and common workflows.

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

Key Points

  • Use race detection in CI
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)

Key Points

  • Validate after decoding
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 } }

Key Points

  • Bound retry budgets
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}");

Key Points

  • Moves transfer ownership
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();

Key Points

  • Clone can be expensive
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");

Key Points

  • Make failure explicit
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}") }

Key Points

  • Exhaustive matching
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

Advanced Questions

Architecture, optimization, and design trade-offs.

Q60Go Architecture

How would you design a resilient Go API service?

Separate transport, business logic, and data access; use deadlines, bounded concurrency, observability, graceful shutdown, and explicit failure policies.

Answer

Define clear contracts and service boundaries.

Use timeouts, load shedding, and circuit-breaking when justified.

Measure latency, errors, saturation, and queue depth.

Syntax

HTTP handler -> service layer -> repository -> database
                 |-> bounded worker pool -> upstream API
Metrics, logs, and traces follow request context

Key Points

  • Layer responsibilities
  • Design for partial failure
Q61Go Concurrency

How would you process millions of records without exhausting memory?

Stream input through bounded batches and a fixed worker pool instead of loading everything into memory.

Answer

Bound every queue and batch.

Propagate cancellation and errors through the pipeline.

Benchmark throughput and memory on representative data.

Syntax

reader -> bounded jobs channel -> N workers -> bounded results -> writer
              context cancellation flows through every stage

Key Points

  • Backpressure is essential
Q62Go Concurrency

How do you avoid deadlocks in a channel pipeline?

Ensure each blocking operation has a possible counterpart or cancellation escape and define channel ownership clearly.

Answer

Document which goroutine closes each channel.

Do not wait before draining a channel that can fill.

Test downstream early-exit cases.

Syntax

select {
case out <- result:
case <-ctx.Done(): return
}

Key Points

  • Plan shutdown and early exits
Q63Go Performance

How do you profile Go CPU and memory?

Use pprof and benchmarks to identify measured bottlenecks before optimizing.

Answer

Profile representative workloads.

Inspect allocations and heap retention.

Compare benchmark results before and after changes.

Syntax

go test -bench=. -benchmem ./...
# Collect CPU/heap profiles with pprof in a controlled environment.

Key Points

  • Measure before optimizing
Q64Go Performance

What causes excessive allocations in Go?

Repeated conversions, formatting, temporary objects, and unbounded buffers can increase allocations; use profiles to locate actual causes.

Answer

Avoid premature optimization.

Reuse buffers only when ownership is clear.

Track allocs/op and bytes/op in benchmarks.

Syntax

func join(parts []string) string { return strings.Join(parts, ",") }

Key Points

  • Use evidence from profiles
Q65Go Reliability

How do you implement idempotency for create requests?

Persist an idempotency key and operation result atomically so duplicate submissions return the same outcome.

Answer

Use a unique constraint on the key.

Reject key reuse with a different request hash.

Make persistence atomic with the business operation.

Syntax

BEGIN TRANSACTION
INSERT idempotency_key, request_hash
perform operation; store response
COMMIT

Key Points

  • Design duplicate request behavior
Q66Go Reliability

How should a service handle overload?

Bound concurrent work, queue capacity, and request duration; reject or shed work deliberately.

Answer

Choose limits from measurements.

Use 429 for client rate limits where appropriate.

Keep health checks responsive during overload.

Syntax

if !limiter.Allow() { http.Error(w, "overloaded", http.StatusServiceUnavailable); return }

Key Points

  • Make overload behavior explicit
Q67Go Security

What security controls matter in Go HTTP services?

Validate inputs, limit body size and time, use TLS, enforce authentication and authorization, and avoid leaking secrets.

Answer

Authentication is not authorization.

Use parameterized database queries.

Keep dependencies updated and logs sanitized.

Syntax

r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
if err := decoder.Decode(&payload); err != nil { http.Error(w, "bad request", 400); return }

Key Points

  • Limit untrusted input
Q68Go Testing

How do table-driven tests and fuzzing help?

Table-driven tests cover named cases compactly; fuzzing explores unexpected inputs to find edge cases.

Answer

Include boundary and regression cases.

Seed fuzzing with known examples.

Use race tests for concurrent code.

Syntax

func TestNormalize(t *testing.T) {
 cases := []struct{in,want string}{{" A ","A"},{"",""}}
 for _, tc := range cases { if got:=normalize(tc.in); got!=tc.want { t.Errorf("got %q want %q",got,tc.want) } }
}
// Fuzz tests use func FuzzXxx(f *testing.F).

Key Points

  • Test invariants, not implementation details
Q69Rust Ownership

What are non-lexical lifetimes?

NLL lets many borrows end at their last use rather than only at the end of a lexical block.

Answer

The compiler tracks actual use where possible.

It does not allow references to invalid memory.

Clear ownership APIs still matter.

Syntax

let mut items = vec![1,2,3];
let first = &items[0];
println!("{first}");
items.push(4);

Key Points

  • Borrow ends after last use
Q70Rust Memory Safety

What is unsafe Rust?

unsafe permits operations the compiler cannot fully verify, such as raw-pointer dereferencing or calling unsafe functions.

Answer

Safe Rust checks still apply outside unsafe operations.

Keep unsafe blocks small and document invariants.

Encapsulate unsafe details behind safe APIs where possible.

Syntax

// unsafe { *raw_ptr } is valid only if pointer validity, alignment,
// lifetime, and aliasing requirements are proven.

Key Points

  • Unsafe shifts proof burden to programmer
Q71Rust Memory Safety

How does Rust prevent data races?

Ownership and Send/Sync rules prevent data races in safe Rust by requiring appropriate synchronization for shared mutation.

Answer

Unsafe code can violate the guarantees.

Logical races remain possible.

Use Mutex, RwLock, or message passing for shared state.

Syntax

let value = std::sync::Arc::new(std::sync::Mutex::new(0));

Key Points

  • Memory safety is not logical correctness
Q72Rust Async

Synchronous versus asynchronous Rust?

Synchronous waits block the current thread; async work returns futures that an executor polls.

Answer

An async function returns a future.

Calling it alone does not complete the operation.

Async helps I/O concurrency, not automatic CPU parallelism.

Syntax

async fn fetch_name() -> Result<String, Error> { Ok(String::from("service")) }
// Run the future using an async runtime.

Key Points

  • An executor drives futures
Q73Rust Async

Why avoid holding a mutex guard across await?

A guard held across suspension can block other tasks and may make a future non-Send.

Answer

Scope the lock before awaiting.

Use async-aware locks only when needed.

An async mutex is not automatically faster.

Syntax

let value = { let guard = state.lock().unwrap(); guard.clone() };
send_async(value).await;

Key Points

  • Keep lock scopes short
Q74Rust Async

How should errors be handled in async services?

Return Result, propagate with ?, and map internal failures to safe transport responses at application boundaries.

Answer

Preserve error sources for diagnostics.

Do not expose internal details to clients.

Use explicit error types at service boundaries.

Syntax

async fn load() -> Result<Item, AppError> {
 let item = repository::get().await?;
 Ok(item)
}

Key Points

  • Separate internal and public errors
Q75Rust Architecture

How would you structure a testable Rust HTTP service?

Separate route handlers, application services, domain types, and persistence adapters; inject dependencies where substitution helps.

Answer

Keep domain logic independent of HTTP.

Use fakes for unit tests and real dependencies for integration tests.

Avoid abstractions with no clear benefit.

Syntax

HTTP route -> application service -> Repository trait
                                  ^              |
                                  |              v
                               test fake     DB adapter

Key Points

  • Test boundaries deliberately
Q76Rust Performance

How do you investigate Rust performance?

Benchmark representative workloads and profile CPU, allocations, contention, and data layout.

Answer

Measure before optimizing.

Cloning String or Vec can allocate.

Use borrowing and layout improvements when profiles justify them.

Syntax

cargo test
cargo bench
# Use an OS/toolchain-appropriate profiler for CPU and allocation data.

Key Points

  • Avoid guesswork
Q77Rust Design

When is Cow useful?

Cow represents borrowed or owned data, avoiding allocations when transformation is unnecessary.

Answer

The owned variant may allocate.

Borrowed data must outlive the Cow.

It is useful for conditional normalization or escaping.

Syntax

fn normalize(s: &str) -> std::borrow::Cow<'_, str> {
 if s.trim()==s { std::borrow::Cow::Borrowed(s) } else { std::borrow::Cow::Owned(s.trim().to_owned()) }
}

Key Points

  • Use when borrowing is usually possible
Q78Rust Design

How do you avoid reference-counted ownership cycles?

Strong Rc/Arc cycles can prevent deallocation; use Weak references for non-owning back-links.

Answer

Rc and Arc count strong references.

Weak does not keep the allocation alive.

Weak is useful for parent pointers and observers.

Syntax

use std::rc::{Rc, Weak};
struct Node { parent: Weak<Node> }

Key Points

  • Avoid strong cycles
Q79Go and Rust Comparison

When choose Go versus Rust for a backend component?

Go often favors straightforward service development and built-in concurrency; Rust offers precise control and compile-time memory safety without a garbage collector.

Answer

Choose based on latency, memory, ecosystem, team expertise, and maintenance.

Both languages can build reliable network services.

Benchmark the actual workload rather than relying on general claims.

Syntax

Go: handlers + goroutines + channels
Rust: ownership + Result + threads/async runtime
Decision: constraints + team + measurements

Key Points

  • Choose for the problem and team

Share this question bank

Send this page to someone preparing for an interview.