1Explain how nil works differently for pointers, slices, maps, channels, functions, and interfaces in Go.
In Go, nil is the zero value for pointers, slices, maps, channels, functions, and interfaces, but operations on those nil values differ by type. A nil pointer can be compared to nil, but dereferencing it panics. A nil slice has length and capacity 0 and can be ranged over and appended to. A nil map can be read from and ranged over, but assigning to it panics. Sending to or receiving from a nil channel blocks forever, and closing a nil channel panics. Calling a nil function panics. An interface is nil only when it has no dynamic type and no dynamic value; an interface holding a typed nil value, such as a nil pointer, is not itself nil.
package main
import "fmt"
type MyErr struct{}
func (*MyErr) Error() string { return "my error" }
func returnsTypedNil() error {
var e *MyErr = nil
return e
}
func main() {
var p *int = nil
var s []int = nil
var m map[string]int = nil
var err error = returnsTypedNil()
fmt.Println(p == nil)
fmt.Println(len(s), cap(s), s == nil)
fmt.Println(m["missing"])
fmt.Println(err == nil)
}
2What are comparable types in Go, and how do comparability rules affect map keys, equality, and generics constraints?
Comparable types in Go are types whose values can be compared with `==` and `!=`. Basic types, pointers, channels, interfaces, and structs/arrays whose fields or elements are comparable are comparable; slices, maps, and functions are not comparable except to `nil`. Map keys must be comparable. Equality follows the type's comparison rules, and interface comparison depends on the dynamic concrete values; comparing two interfaces with the same dynamic type panics if that type is not comparable. Comparing such an interface to nil or to an interface with a different dynamic type does not panic. In generics, the predeclared `comparable` constraint allows type parameters to be compared with `==`/`!=` and used as map keys.
package main
import "fmt"
type Point struct{ X, Y int } // comparable
type Bag struct{ Items []string } // not comparable because of slice field
func Contains[T comparable](xs []T, target T) bool {
for _, x := range xs {
if x == target {
return true
}
}
return false
}
func main() {
p1, p2 := Point{1, 2}, Point{1, 2}
fmt.Println(p1 == p2)
m := map[Point]string{p1: "value"}
fmt.Println(m[p2])
fmt.Println(Contains([]string{"a", "b"}, "b"))
var a any = []int{1}
var b any = []int{1}
_, _ = a, b
// fmt.Println(a == b) // panic: comparing uncomparable type []int
}
3How does Go represent bytes, runes, and UTF-8 encoded text, and why can len(s) differ from the number of user-visible characters?
In Go, `byte` is an alias for `uint8` and represents one raw byte, while `rune` is an alias for `int32` and represents a Unicode code point. A `string` is a read-only sequence of bytes, commonly UTF-8 encoded text but able to contain arbitrary bytes. `len(s)` returns the number of bytes, not runes or user-visible characters. Indexing a string returns a byte; ranging over a string decodes UTF-8 and yields byte indexes plus runes. `len(s)` can differ from the number of visible characters because UTF-8 may use multiple bytes per code point and because one user-visible character may be composed of multiple code points, such as combining marks or emoji sequences.
package main
import "fmt"
func main() {
s := "é🙂"
fmt.Println(len(s)) // bytes: é is 2 bytes, 🙂 is 4 bytes
fmt.Println(len([]rune(s))) // Unicode code points
fmt.Printf("first byte: %x\n", s[0])
for i, r := range s {
fmt.Printf("byte index %d: %q U+%04X\n", i, r, r)
}
}
4How do type aliases differ from defined types, and when would you use each?
A defined type, such as `type UserID int64`, creates a new distinct type with `int64` as its underlying type. It is not freely assignable to `int64` without conversion and can have its own methods. A type alias, such as `type UserID = int64`, is just another name for the same type, so type identity and assignability are preserved. Use defined types for domain modeling, type safety, and methods; use aliases mainly for refactoring, migration, or compatibility without introducing a new type.
type UserID int64 // defined type
type AccountID = int64 // alias
func takeInt64(x int64) {}
var u UserID = 10
var a AccountID = 20
takeInt64(int64(u)) // explicit conversion required
takeInt64(a) // ok: AccountID is exactly int64
func (u UserID) String() string {
return fmt.Sprintf("user:%d", u)
}
5How does Go treat floating-point special values and what equality pitfalls matter in backend systems?
Go `float32` and `float64` use IEEE-754-style behavior, including special values such as positive/negative infinity and NaN. For `float64`, helpers include `math.Inf`, `math.IsInf`, `math.NaN`, and `math.IsNaN`. NaN is not equal to anything, including itself, so `x == x` is false when `x` is NaN. Exact equality on computed floats is also risky because rounding and precision can make mathematically equal values differ; use domain-appropriate tolerances or avoid floats for exact business values like money. Floats are allowed as map keys, but NaN keys are problematic because map lookup depends on equality and NaN does not compare equal, even to itself.
nan := math.NaN()
fmt.Println(nan == nan)
fmt.Println(math.IsNaN(nan))
m := map[float64]string{nan: "bad key"}
fmt.Println(m[nan]) // lookup fails because nan != nan
6Describe struct embedding in Go and how promoted fields and methods behave.
Struct embedding in Go means declaring a field by its type without an explicit field name, for example `type User struct { Person }`. The embedded value is still a real field, accessible as `u.Person`, but its exported/accessible fields and methods may be promoted so callers can write selectors like `u.Name` or `u.Greet()` as shorthand for going through the embedded field. Embedding is composition, not classical inheritance: the outer type is not automatically a subtype of the embedded type. If promoted selectors conflict, Go does not guess; ambiguous names must be qualified or are not selectable through the outer value.
package main
import "fmt"
type Person struct {
Name string
}
func (p Person) Greet() string {
return "hi " + p.Name
}
type User struct {
Person // embedded field; field name is Person
ID int
}
func main() {
u := User{Person: Person{Name: "Ana"}, ID: 10}
fmt.Println(u.Name) // promoted field: u.Person.Name
fmt.Println(u.Greet()) // promoted method: u.Person.Greet()
fmt.Println(u.Person.Name) // explicit qualification still works
}
7Design a thread-safe TTL cache exposed behind a Go HTTP service.
Store each value with its expiry and protect shared state with a mutex or sharded locks. Check expiry on reads, reclaim stale entries periodically, bound memory and pass a clock into tests. Keep slow work outside the lock.
8Explain slice growth during append at a conceptual level and the performance implications of repeated reallocation.
When append adds elements to a slice, it writes into the existing backing array if the slice has enough capacity. If capacity is insufficient, Go allocates a larger backing array, copies the existing elements, writes the new elements, and returns a slice header pointing to the new storage. The exact growth policy is implementation-dependent, but conceptually capacity grows enough to make repeated append amortized efficient. Repeated reallocations still cost CPU for copying, create allocations, increase GC pressure, and may break sharing with old slice aliases. If you know the expected size, preallocate with make([]T, 0, n) when building by append or make([]T, n) when filling by index to reduce reallocations.
package main
func collectNoPrealloc(input []int) []int {
var out []int
for _, v := range input {
out = append(out, v*2)
}
return out
}
func collectPrealloc(input []int) []int {
out := make([]int, 0, len(input))
for _, v := range input {
out = append(out, v*2)
}
return out
}
9When would you choose a REST-style HTTP API versus gRPC for a Go service?
Choose a REST-style HTTP API when resource semantics, browser access, easy inspection and broad third-party integration matter. HTTP caching and familiar tools can be useful, though a JSON endpoint is not automatically a well-designed REST API. Choose gRPC when controlled clients benefit from generated typed contracts, compact protobuf messages and unary or bidirectional streaming RPCs. It can reduce serialization overhead, but end-to-end performance still depends on workload and dependencies. Check ingress, load balancer, observability and browser support; browser clients often need gRPC-Web or a gateway, with corresponding limitations. For either option, design authentication, deadlines, cancellation, pagination/backpressure, idempotency and error semantics explicitly. Evolve schemas compatibly and test old clients. A public HTTP facade and internal gRPC service can coexist when the extra translation layer is justified; Go itself does not force either choice.
10How would you choose between signed access tokens and opaque server-managed sessions?
Signed access tokens allow services to validate claims locally, reducing dependency on a session lookup, but permissions can remain stale until expiry unless revocation or introspection adds state. I would use short lifetimes, controlled key rotation and strict validation of signature algorithm, issuer, audience and expiry. A signature does not encrypt claims, so tokens should not contain secrets. Opaque high-entropy session IDs reference server-side state, making logout, revocation and permission changes easier to apply centrally, at the cost of a highly available lookup store and its latency. For browser applications, secure HttpOnly cookies, appropriate SameSite settings and CSRF defenses matter regardless of whether the credential is opaque or signed. I would choose based on trust boundaries, revocation urgency and client needs; a hybrid with short-lived access tokens and server-controlled refresh sessions is often useful.
11How do errors.Is, errors.As, and %w work in Go error wrapping chains?
`fmt.Errorf` with `%w` creates a new error that wraps an underlying error while adding context. Wrappers expose underlying errors through `Unwrap`, forming a chain or tree that the standard library can inspect. `errors.Is(err, target)` checks whether `err` or anything it wraps matches a target error. `errors.As(err, &target)` checks whether `err` or anything it wraps is assignable to the target type and stores the matched value in the provided pointer.
12What are sentinel errors, and what are the tradeoffs versus custom typed errors or richer domain error models?
A sentinel error is a named error value, often a package-level variable such as `var ErrNotFound = errors.New("not found")`, used to represent a specific condition that callers can test, typically with `errors.Is` when wrapping is possible. Sentinels are simple and useful for broad stable categories, but exported sentinels become part of the API and can couple callers to particular values. Custom typed errors can carry structured fields and be found with `errors.As`. Richer domain error models classify failures by kind/code and may include safe messages or metadata, which is useful when callers need stable behavior beyond one fixed error value.
13How should a Go backend map internal errors to useful client responses while still giving operators diagnosable signals?
A Go backend should translate internal errors at an application or transport boundary into stable, client-safe categories and responses. Those categories should map to appropriate HTTP status codes or equivalent transport statuses, with safe messages and machine-readable codes rather than raw internal errors. Operators should still get diagnostic information through structured logs, traces, metrics, correlation/request IDs, and preserved underlying causes. Logging is usually best done once at a boundary that has request context, to avoid both missing failures and noisy duplicate logs.
type ErrorCode string
const (
CodeNotFound ErrorCode = "not_found"
CodeInvalid ErrorCode = "invalid_argument"
CodeInternal ErrorCode = "internal"
)
type AppError struct {
Code ErrorCode
Message string // safe for clients
Err error // internal cause
}
func (e *AppError) Error() string { return string(e.Code) + ": " + e.Err.Error() }
func (e *AppError) Unwrap() error { return e.Err }
func statusFor(code ErrorCode) int {
switch code {
case CodeNotFound:
return 404
case CodeInvalid:
return 400
default:
return 500
}
}
// Handler boundary idea:
// - call service
// - classify or convert error to AppError
// - log original error with request_id and safe request context
// - return {"code":"not_found","message":"user not found","request_id":"..."}
14How would you prevent many requests from rebuilding the same expired cache entry simultaneously?
A stampede happens when a popular entry expires or disappears and many requests simultaneously hit the origin to rebuild it. In one Go process, I would coalesce loads by key with singleflight, recheck the cache inside the loader, and let concurrent callers share the result. That suppresses duplicate in-flight calls; it is not itself a persistent cache. TTL jitter prevents many different keys expiring together, while refresh-ahead or stale-while-revalidate can reduce waiting when serving bounded-stale data is acceptable. Across instances, local singleflight still allows one origin call per instance, so a carefully designed shared lease or another distributed coordination mechanism may be needed. Refreshes require deadlines, ownership-safe lease release and bounded retries, with failure behavior that does not trigger a retry storm. Caller cancellation should stop waiting without necessarily aborting useful shared work. I would monitor origin concurrency and stale-data age.
15When would a Go backend put work on a durable message queue instead of completing it in the original HTTP request?
I would use a durable queue for work whose result is not needed immediately, such as generating a large report or delivering a notification, especially when bursts, dependency outages or retries should outlive the HTTP request and process. The API should acknowledge acceptance only after durable recording, return a job identifier and expose status or completion notification. Workers need bounded concurrency, timeouts, retry backoff and a dead-letter or investigation path for persistent failures. Since delivery is commonly at least once, handlers and external side effects must be idempotent using stable operation identifiers. If accepting the job also changes database state, a transactional outbox can prevent committing one action while losing the other. I would monitor queue age and capacity; a queue postpones overload rather than eliminating it. Short operations requiring an immediate result may be simpler and faster synchronously.