Language Fundamentals & Types·Q1·Medium
Every variable in Go is initialized to its type's zero value: 0 for numbers, false for bools, "" for strings, and nil for pointers, slices, maps, channels, functions and…
Language Fundamentals & Types·Q2·Medium
new(T) works for any type. It allocates a zeroed T and returns a *T . make only works for slices, maps and channels. It initializes the runtime data structure behind…
Language Fundamentals & Types·Q3·Hard
type Size int64 const ( _ = iota // iota = 0, skipped KB Size = 1 << (10 * iota) // iota = 1 MB // iota = 2: repeats the expression GB // iota = 3 ) const ( A, B = iota,…
Language Fundamentals & Types·Q4·Hard
Untyped constants are exact values that live only at compile time. The spec requires at least 256 bits of precision for integer constants. A constant only gets a…
Language Fundamentals & Types·Q5·Medium
A typed constant follows the same strict rules as a variable of that type. Go never converts between named types implicitly. An untyped constant can be assigned to any…
Language Fundamentals & Types·Q6·Medium
var db *sql.DB func initDB() error { db, err := sql.Open("postgres", dsn) // BUG: declares a new local db if err != nil { return err } return db.Ping() } // Later:…
Language Fundamentals & Types·Q7·Hard
func parse(s string) (n int, err error) { if s != "" { n, err := strconv.Atoi(s) if err != nil { return // compile error: result parameter err not in scope at return } _…
Language Fundamentals & Types·Q8·Hard
i := 0 s := []int{10, 20} i, s[i] = 1, 5 fmt.Println(i, s) a, b := 1, 2 a, b = b, a+b fmt.Println(a, b) Output: 1 [5 20] 2 3 A tuple assignment happens in two phases .…
Language Fundamentals & Types·Q9·Medium
A conversion , T(x) , is checked at compile time: the compiler rejects it unless the types are convertible. It may still do work at run time, such as copying bytes for…
Language Fundamentals & Types·Q10·Hard
func describe(x any) string { switch v := x.(type) { case nil: return "nil interface" case int, int64: // v has type any here, NOT int return fmt.Sprintf("integer %v",…
Language Fundamentals & Types·Q11·Medium
s := "héllo" fmt.Println(len(s)) fmt.Println(s[1]) fmt.Println(utf8.RuneCountInString(s)) for i, r := range s { fmt.Printf("%d:%c ", i, r) } Output: 6 195 5 0:h 1:é 3:l…
Language Fundamentals & Types·Q12·Hard
s := "a\xffb" fmt.Println(len(s)) // 3 for i, r := range s { fmt.Printf("%d:%U ", i, r) } // 0:U+0061 1:U+FFFD 2:U+0062 fmt.Println(string(rune(65))) // "A"…
Language Fundamentals & Types·Q13·Hard
Converting []byte(s) or string(b) normally allocates and copies the data. This is required because strings are immutable and byte slices are not. The compiler skips the…
Language Fundamentals & Types·Q14·Medium
func main() { x := 1 defer fmt.Println("deferred arg:", x) defer func() { fmt.Println("closure:", x) }() x = 2 fmt.Println("body:", x) } Output: body: 2 closure: 2…
Language Fundamentals & Types·Q15·Medium
Deferred calls are pushed onto a stack for each function call and run in LIFO order when the function returns, whether it returns normally or by panicking. A defer runs…
Language Fundamentals & Types·Q16·Hard
func f() (n int) { defer func() { n *= 2 }() return 3 } func g() int { n := 3 defer func() { n *= 2 }() return n } func safeDiv(a, b int) (q int, err error) { defer…
Language Fundamentals & Types·Q17·Hard
type T struct{ name string } func (t T) ValPrint() { fmt.Println("val:", t.name) } func (t *T) PtrPrint() { fmt.Println("ptr:", t.name) } func main() { t := T{"a"} defer…
Language Fundamentals & Types·Q18·Hard
recover stops a panic only when it is called directly by a deferred function while the goroutine is panicking. In every other situation it returns nil and does nothing.…
Language Fundamentals & Types·Q19·Medium
panic: yes. Deferred calls run while the stack unwinds, and that is where recover can happen. runtime.Goexit: yes. It ends the current goroutine and runs its defers.…
Language Fundamentals & Types·Q20·Hard
package main import "fmt" var a = c + b var b = f() var c = 1 func f() int { fmt.Println("f called, c =", c) return 2 } func init() { fmt.Println("init: a =", a) } func…
Language Fundamentals & Types·Q21·Medium
Order of initialization: Imported packages are initialized first, depth-first. Each package is initialized exactly once , no matter how many packages import it. Inside a…
Language Fundamentals & Types·Q22·Medium
An unlabeled break ends the innermost for , switch or select . Inside a select or switch that sits in a loop, a plain break leaves only the select or switch , and the…
Language Fundamentals & Types·Q23·Hard
Go has goto , but with two rules that keep it safe: It can't jump over a variable declaration if the variable would be in scope at the label. That would create a…
Language Fundamentals & Types·Q24·Medium
switch x := 2; x { case 1: fmt.Println("one") case 2: fmt.Println("two") fallthrough case 3: fmt.Println("three") fallthrough case 100: fmt.Println("hundred") default:…
Language Fundamentals & Types·Q25·Hard
Comparable types ( == and != work): booleans, numbers, strings, pointers, channels, interfaces, arrays of comparable elements, and structs whose fields are all…
Language Fundamentals & Types·Q26·Hard
Two struct values are equal when every field is equal, compared in the order the fields are declared. Unexported fields are compared too. Blank ( _ ) fields are skipped.…
Language Fundamentals & Types·Q27·Hard
comparable is a built-in constraint that permits == and != on a type parameter, so it can be used as a map key: func Index[T comparable](s []T, v T) int { for i, x :=…
Language Fundamentals & Types·Q28·Hard
type Speaker interface{ Speak() string } type Dog struct{ name string } func (d *Dog) Speak() string { return d.name + ": woof" } func main() { // var s Speaker =…
Language Fundamentals & Types·Q29·Hard
An expression is addressable if you can take its address with & . That includes variables, pointer dereferences, slice elements, and fields or elements of addressable…
Language Fundamentals & Types·Q30·Hard
Embedding promotes the embedded type's fields and methods to the outer type. For a struct S : If S embeds T : the method set of S gets T 's value methods. The method set…
Language Fundamentals & Types·Q31·Hard
type MyErr struct{} func (*MyErr) Error() string { return "boom" } func do(fail bool) error { var p *MyErr // nil pointer if fail { p = &MyErr{} } return p // BUG:…
Language Fundamentals & Types·Q32·Medium
type Celsius float64 creates a new, distinct type . It has the same underlying type, but it doesn't inherit the methods of the original named type, and you need explicit…
Language Fundamentals & Types·Q33·Hard
arr := [3]int{1, 2, 3} for i, v := range arr { if i == 0 { arr[1] = 100 } fmt.Print(v, " ") } fmt.Println() sl := []int{1, 2, 3} for i, v := range sl { if i == 0 { sl[1]…
Language Fundamentals & Types·Q34·Hard
var x int8 = 127 x++ fmt.Println(x) // -128: signed overflow wraps (two's complement), no panic var u uint8 = 0 u-- fmt.Println(u) // 255 fmt.Println(-7 / 2, -7 % 2) //…
Language Fundamentals & Types·Q35·Hard
var fns []func() for i := 0; i < 3; i++ { fns = append(fns, func() { fmt.Print(i, " ") }) } for _, f := range fns { f() } var ptrs []*int for i := range 3 { // range…
Language Fundamentals & Types·Q36·Hard
func Countdown(n int) iter.Seq[int] { // iter.Seq[V] is func(yield func(V) bool) return func(yield func(int) bool) { defer fmt.Println("iterator cleanup") for i := n; i…
Language Fundamentals & Types·Q37·Hard
type Bad struct { a bool // offset 0, then 7 bytes padding b int64 // offset 8 c bool // offset 16, then 7 bytes tail padding } type Good struct { b int64 // offset 0 a…
Language Fundamentals & Types·Q38·Hard
type P struct{ X int } func (p P) Get() int { return p.X } func (p *P) Set(v int) { p.X = v } func main() { p := P{1} get := p.Get // method value: a copy of p is bound…
Language Fundamentals & Types·Q39·Hard
var s uint = 33 var i = 1 << s // 1 takes type int var j int32 = 1 << s // 1 takes type int32: the bit is shifted out, j == 0 var k = uint64(1 << s) // 1 takes type…
Arrays, Slices, Maps & Strings·Q40·Medium
A slice is a small struct of three words, {ptr *T, len int, cap int} . It holds a pointer to a backing array, the number of elements you can see ( len ), and how many…
Arrays, Slices, Maps & Strings·Q41·Hard
func add(s []int) { s = append(s, 4) s[0] = 100 } func main() { s := make([]int, 3, 4) add(s) fmt.Println(s, len(s), cap(s)) fmt.Println(s[:4]) t := []int{1, 2, 3} //…
Arrays, Slices, Maps & Strings·Q42·Hard
When len + n > cap , append calls runtime.growslice . Since Go 1.20 the rule ( nextslicecap ) is: If the needed length is more than twice the old cap, use the needed…
Arrays, Slices, Maps & Strings·Q43·Hard
x := make([]int, 0, 5) x = append(x, 1, 2, 3) y := append(x, 4) z := append(x, 5) fmt.Println(x, y, z) Output: [1 2 3] [1 2 3 5] [1 2 3 5] x has len 3 and cap 5. Both…
Arrays, Slices, Maps & Strings·Q44·Medium
a[low:high:max] makes a slice with len = high-low and cap = max-low . The constraint is 0 <= low <= high <= max <= cap(a) . A plain a[low:high] keeps all the capacity up…
Arrays, Slices, Maps & Strings·Q45·Medium
var s []int is nil : ptr is nil, len and cap are 0. s := []int{} or make([]int, 0) is empty but non-nil : ptr points at a zero-size allocation (often runtime.zerobase ).…
Arrays, Slices, Maps & Strings·Q46·Medium
copy(dst, src) copies min(len(dst), len(src)) elements and returns that count. It uses len, not cap . So copying into make([]T, 0, n) copies nothing, which is a common…
Arrays, Slices, Maps & Strings·Q47·Medium
An array's length is part of its type ( [4]int and [5]int are different types). An array is a value : assigning it, passing it, or ranging over it copies every element.…
Arrays, Slices, Maps & Strings·Q48·Hard
arr := [3]int{1, 2, 3} for i, v := range arr { arr[2] = 100 if i == 2 { fmt.Println("array:", v) } } sl := []int{1, 2, 3} for i, v := range sl { sl[2] = 100 if i == 2 {…
Arrays, Slices, Maps & Strings·Q49·Hard
A subslice keeps the entire backing array reachable, not just the part you can see. If you read a 10 MB file and keep data[:16] in a long-lived cache, all 10 MB stays…
Arrays, Slices, Maps & Strings·Q50·Medium
There are three common patterns: Order-preserving delete: O(n), using append or copy. Unordered delete: O(1), swap with the last element. In-place filter: O(n), no…
Arrays, Slices, Maps & Strings·Q51·Medium
Slices, maps, and functions are not comparable . You can compare them only to nil . The language designers left out == for slices on purpose, because it is ambiguous:…
Arrays, Slices, Maps & Strings·Q52·Medium
make([][]int, n) creates only the outer slice of n nil rows. Writing grid[0][0] panics until you allocate each row. There are two approaches. // 1) Row-per-allocation:…
Arrays, Slices, Maps & Strings·Q53·Hard
If a function is declared as func Filter[E any](s []E) []E , then passing a named slice type like type IDs []int returns plain []int . The caller loses the named type…
Arrays, Slices, Maps & Strings·Q54·Medium
Go 1.21 added slices and maps to the standard library. Go 1.23 added iterator-returning functions based on iter.Seq / iter.Seq2 and range-over-func. s := []int{3, 1, 4,…
Arrays, Slices, Maps & Strings·Q55·Hard
The classic runtime map ( runtime.hmap ) is a hash table with 2^B buckets : Each bucket ( bmap ) holds 8 entries . It starts with tophash [8]uint8 , the top 8 bits of…
Arrays, Slices, Maps & Strings·Q56·Hard
Go 1.24 replaced the bucket-chaining map with an implementation based on Swiss Tables (Google's Abseil design), in internal/runtime/maps . The design has several parts:…
Arrays, Slices, Maps & Strings·Q57·Medium
The spec says iteration order is unspecified . The runtime goes further and deliberately randomizes it: each range starts at a random position (in the classic map, a…
Arrays, Slices, Maps & Strings·Q58·Medium
Yes, within one goroutine. The spec defines the behaviour: Deleting an entry that has not been reached yet means it will not be produced. Deleting the current key is…
Arrays, Slices, Maps & Strings·Q59·Hard
Built-in maps are not safe for concurrent use if at least one goroutine writes. Concurrent reads alone are fine. The runtime has a cheap best-effort check (a hashWriting…
Arrays, Slices, Maps & Strings·Q60·Hard
The sync.Map docs name two cases where it wins: The entry for a key is written once and read many times , as in caches that only grow. Many goroutines read, write, and…
Arrays, Slices, Maps & Strings·Q61·Medium
Map elements are not addressable . m["k"] gives you a copy of the value, and assigning to a field of a temporary copy would do nothing. So the compiler rejects it:…
Arrays, Slices, Maps & Strings·Q62·Medium
Because the runtime moves map entries . When a map grows (classic evacuation, or a Swiss-table split), entries are rehashed and copied to new memory. A pointer from…
Arrays, Slices, Maps & Strings·Q63·Hard
Keys must be comparable : booleans, numbers, strings, pointers, channels, interfaces, and arrays or structs made only of comparable types. Slices, maps, and functions…
Arrays, Slices, Maps & Strings·Q64·Hard
No. delete marks slots as empty (or as tombstones in Swiss tables), but the bucket or group memory is never given back. A map that once held 1M entries keeps its…
Arrays, Slices, Maps & Strings·Q65·Medium
clear (Go 1.21) has different semantics depending on the type: Map: deletes every entry, so len becomes 0. It is the only way to remove NaN keys, and it is faster than…
Arrays, Slices, Maps & Strings·Q66·Medium
A map variable is a pointer to a runtime header . Passing it copies the pointer, so inserts and deletes inside the callee are visible to the caller, without needing *map…
Arrays, Slices, Maps & Strings·Q67·Hard
A string is a two-word header, {ptr *byte, len int} , pointing at read-only bytes. Immutability means strings can be shared freely: substrings and assignments copy no…
Arrays, Slices, Maps & Strings·Q68·Medium
s := "héllo" fmt.Println(len(s), utf8.RuneCountInString(s)) fmt.Println(s[1], string(s[1])) for i, r := range s { fmt.Printf("%d:%c ", i, r) } fmt.Println()…
Arrays, Slices, Maps & Strings·Q69·Medium
Because strings are immutable, s += x in a loop allocates a new string and copies everything built so far each time, which is O(n²) . The options compare like this: +…
Arrays, Slices, Maps & Strings·Q70·Hard
Go 1.20 added the supported primitives unsafe.String , unsafe.StringData and unsafe.SliceData . They replace the old reflect.StringHeader / SliceHeader hacks, which are…
Arrays, Slices, Maps & Strings·Q71·Medium
Go has no built-in set type. The idiom is map[T]struct{} . The empty struct takes zero bytes , so values cost nothing, and the type makes the intent clear. map[T]bool…
Arrays, Slices, Maps & Strings·Q72·Hard
var ptrs []*int for _, v := range []int{1, 2, 3} { ptrs = append(ptrs, &v) } var funcs []func() for i := 0; i < 3; i++ { funcs = append(funcs, func() { fmt.Print(i, " ")…
Arrays, Slices, Maps & Strings·Q73·Hard
base := make([]int, 0, 4) m := map[string][]int{} m["a"] = append(base, 1) m["b"] = append(base, 2) fmt.Println(m["a"], m["b"]) m["a"] = append(m["a"], 10)…
Arrays, Slices, Maps & Strings·Q74·Hard
func main() { var p *[3]int fmt.Println(len(p)) for i := range p { fmt.Print(i, " ") } fmt.Println() for i := range 3 { // Go 1.22 range-over-int fmt.Print(i, " ") }…
Arrays, Slices, Maps & Strings·Q75·Hard
Since Go 1.23 a for range loop can take a function of type func(yield func(K, V) bool) (that is, iter.Seq2[K, V] ), func(yield func(V) bool) ( iter.Seq[V] ) or…
Arrays, Slices, Maps & Strings·Q76·Hard
unique.Make[T comparable](v T) Handle[T] canonicalizes (interns) values. All calls with equal values return handles that point to the same single copy. Comparing two…
Interfaces, Methods & Embedding·Q77·Hard
An interface value is a two-word structure. The runtime uses two layouts: eface (empty interface, any ): {_type *_type; data unsafe.Pointer} . It holds only the dynamic…
Interfaces, Methods & Embedding·Q78·Hard
An itab pairs one (interface type, concrete type) combination with the method pointers the concrete type provides for that interface. When the compiler can see a…
Interfaces, Methods & Embedding·Q79·Medium
package main import "fmt" type T struct{} func main() { var p *T = nil var i any = p var j any fmt.Println(p == nil) // ? fmt.Println(i == nil) // ? fmt.Println(j ==…
Interfaces, Methods & Embedding·Q80·Hard
type MyErr struct{ Msg string } func (e *MyErr) Error() string { return e.Msg } func validate(ok bool) error { var e *MyErr if !ok { e = &MyErr{"invalid"} } return e //…
Interfaces, Methods & Embedding·Q81·Medium
The spec defines method sets as follows: The method set of T contains methods declared with receiver T . The method set of *T contains methods with receiver T and *T .…
Interfaces, Methods & Embedding·Q82·Hard
type Counter struct{ n int } func (c *Counter) Inc() { c.n++ } m := map[string]Counter{"k": {}} // m["k"].Inc() // error: cannot call pointer method Inc on Counter //…
Interfaces, Methods & Embedding·Q83·Medium
Use a pointer receiver when any of these apply: The method mutates the receiver. The struct is large, so copying it on every call is expensive. The struct contains…
Interfaces, Methods & Embedding·Q84·Medium
The single-value form panics when the assertion fails. The panic message looks like interface conversion: interface {} is string, not int . The comma-ok form never…
Interfaces, Methods & Embedding·Q85·Medium
func describe(x any) string { switch v := x.(type) { case nil: return "nil" case int, int64: return fmt.Sprintf("integer %T", v) // v has type any here case error:…
Interfaces, Methods & Embedding·Q86·Medium
No. Embedding is composition with automatic delegation . An embedded field is an ordinary field named after its type, and the compiler promotes its fields and methods so…
Interfaces, Methods & Embedding·Q87·Hard
type Base struct{} func (Base) Name() string { return "Base" } func (b Base) Greet() string { return "Hello from " + b.Name() } type Derived struct{ Base } func…
Interfaces, Methods & Embedding·Q88·Hard
For a struct S : If S embeds T , the method sets of S and *S include the promoted methods with receiver T . Only *S also includes those with receiver *T . If S embeds *T…
Interfaces, Methods & Embedding·Q89·Hard
Selector resolution uses depth . The name at the shallowest depth wins and shadows any deeper ones. If two or more names exist at the same shallowest depth, the selector…
Interfaces, Methods & Embedding·Q90·Medium
An interface can embed other interfaces. The resulting method set is the union of all their methods. This is how the standard library builds larger contracts from small…
Interfaces, Methods & Embedding·Q91·Hard
Embedding an interface in a struct makes the struct satisfy the interface automatically. You then override only the methods you care about, and all the others delegate…
Interfaces, Methods & Embedding·Q92·Medium
any is an alias for interface{} (Go 1.18). Every type satisfies it, which is why it throws away static type information. Legitimate uses: Truly heterogeneous data:…
Interfaces, Methods & Embedding·Q93·Medium
It is a compile-time assertion that *MyWriter implements io.Writer . Go interfaces are satisfied implicitly, so if someone changes a method signature, the type silently…
Interfaces, Methods & Embedding·Q94·Medium
Because satisfaction is structural and there is no implements keyword, a type can satisfy an interface that was written after it, in a package it has never heard of. The…
Interfaces, Methods & Embedding·Q95·Medium
Accept interfaces: parameters should ask for the smallest behaviour needed ( io.Reader rather than *os.File ). Callers can then pass files, buffers, network connections…
Interfaces, Methods & Embedding·Q96·Medium
"The bigger the interface, the weaker the abstraction" (Rob Pike). A one-method interface is easy to satisfy, so many types implement it, and it composes well. io.Reader…
Interfaces, Methods & Embedding·Q97·Hard
type Celsius float64 func (c Celsius) String() string { return fmt.Sprintf("%v C", c) // infinite recursion -> stack overflow } %v on a value that implements…
Interfaces, Methods & Embedding·Q98·Hard
error is a one-method interface. Go offers three styles, each for a different need: Sentinel errors ( var ErrNotFound = errors.New(...) ), compared by identity. Typed…
Interfaces, Methods & Embedding·Q99·Hard
Two interface values are equal when their dynamic types are identical and their dynamic values are equal, or when both are nil. If the dynamic types are the same and…
Interfaces, Methods & Embedding·Q100·Hard
Often it does. The data word must be a pointer, so non-pointer values are copied into memory. The runtime helpers ( convT , convT64 , convTstring ) allocate on the heap…
Interfaces, Methods & Embedding·Q101·Hard
type T struct{ n int } func (t T) ShowVal() { fmt.Println("val", t.n) } func (t *T) ShowPtr() { fmt.Println("ptr", t.n) } func main() { t := T{n: 1} fv := t.ShowVal //…
Interfaces, Methods & Embedding·Q102·Medium
You can declare a method only on a defined type declared in the same package . The receiver's base type must not be a pointer type or an interface type. The base type…
Interfaces, Methods & Embedding·Q103·Medium
A function accepts a small interface, then uses a type assertion to check at runtime whether the value also implements a richer interface. If it does, the function takes…
Interfaces, Methods & Embedding·Q104·Hard
Since Go 1.18, an interface defines a type set . A basic interface (methods only) can be used both as a value type and as a constraint. An interface that contains type…
Interfaces, Methods & Embedding·Q105·Medium
These are three different mechanisms: Defined type type B A : B has the same underlying type as A but none of A's declared methods . (If A is an interface type, B has…
Interfaces, Methods & Embedding·Q106·Medium
A function type can have methods, so a plain function can be adapted to satisfy a single-method interface without writing a struct: // net/http type Handler interface {…
Interfaces, Methods & Embedding·Q107·Hard
type V struct{ n int } func (v V) Get() int { return 42 } // value receiver, never reads v.n type Getter interface{ Get() int } //go:noinline func call(g Getter) int {…
Interfaces, Methods & Embedding·Q108·Hard
type P struct{ X int } func main() { var i any = P{1} // i.(P).X = 2 // compile error: cannot assign to i.(P).X // // (neither addressable nor a map index expression) p…
Interfaces, Methods & Embedding·Q109·Hard
type Setter interface{ Set(string) } type Settable struct{ v string } func (s *Settable) Set(v string) { s.v = v } // Attempt 1: T Setter func Bad[T Setter](xs []string)…
Interfaces, Methods & Embedding·Q110·Hard
Add an unexported method to the interface. Method names that are not exported are qualified by their package, so a type in another package cannot declare a method with…
Interfaces, Methods & Embedding·Q111·Hard
// Go 1.22+: reflect.TypeFor works for interface types directly writerT := reflect.TypeFor[io.Writer]() fmt.Println(reflect.TypeFor[*bytes.Buffer]().Implements(writerT))…
Generics·Q112·Medium
Before Go 1.18 you had two choices for reusable code: write it once per type (or with go generate ), or accept interface{} and give up static typing. With any the…
Generics·Q113·Medium
For a single argument they behave almost the same. The differences show up in three places: Same type across parameters and results: func Pick[T fmt.Stringer](a, b T) T…
Generics·Q114·Medium
A constraint is an interface that limits which type arguments are allowed. Since Go 1.18 an interface defines a type set . It can list methods, type terms ( int | string…
Generics·Q115·Medium
~T means "every type whose underlying type is T". Without the tilde, only the exact type T itself matches. Named types such as type Celsius float64 or time.Duration…
Generics·Q116·Hard
Every interface denotes a type set : A method element gives the set of all types that have that method. A union A | B gives the union of the two sets. Elements on…
Generics·Q117·Hard
comparable is a predeclared constraint for types that support == and != . It covers booleans, numbers, strings, pointers, channels, arrays and structs of comparable…
Generics·Q118·Hard
An operation is allowed on a value of type T only if it is valid for every type in T's type set, and the spec explicitly permits it: Operators ( + , < , == ) work if…
Generics·Q119·Hard
Go infers type arguments in two ways: Function argument inference unifies parameter types with argument types. Constraint type inference derives a parameter from another…
Generics·Q120·Medium
No. A generic function is not a value until it is instantiated . There are no "generic function values", so f := Map fails with cannot use generic function Map without…
Generics·Q121·Medium
You cannot write return nil , and you cannot write T{} for an arbitrary T . nil is not valid for int, and composite literals need a core type. Use one of these idioms:…
Generics·Q122·Hard
func IsNil[T any](v T) bool { return any(v) == nil } func main() { var p *int var err error fmt.Println(IsNil(p), IsNil[any](nil), IsNil(err), IsNil[error](nil)) }…
Generics·Q123·Medium
type MyInt int func Describe[T any](v T) string { switch any(v).(type) { case int: return "int" case fmt.Stringer: return "Stringer" default: return "other" } } func…
Generics·Q124·Hard
Methods can use their receiver type's parameters, but a method cannot declare new type parameters of its own. func (l List[T]) Map[U any](f func(T) U) List[U] is…
Generics·Q125·Medium
The receiver must list the type's parameters by name, and you may rename them. You cannot repeat or tighten the constraints in the receiver, and you cannot specialize a…
Generics·Q126·Hard
The main restrictions, several of which exist to keep method sets statically known: No embedding a type parameter: type Wrapper[T any] struct{ T } fails with "embedded…
Generics·Q127·Hard
Problem: you want to create values of type T inside a generic function and call a method that has a pointer receiver , such as UnmarshalText or Set . T itself does not…
Generics·Q128·Hard
An interface can itself have type parameters. That lets a constraint refer to the type being constrained, similar to F-bounded polymorphism or Java's Comparable<T> . It…
Generics·Q129·Hard
The goal is to preserve the caller's named slice type . With []E in and []E out, a named type like type IDs []int comes back as a plain []int , and its methods are lost.…
Generics·Q130·Hard
Go uses a hybrid of the two classic strategies. Full monomorphization (C++, Rust) makes one copy per type. Full boxing (Java) makes one copy for everything. Go instead…
Generics·Q131·Medium
Interviewers want judgment, not enthusiasm. Guidance, broadly following Ian Lance Taylor's "When To Use Generics": When you only call methods: if the function just calls…
Generics·Q132·Medium
type Stack[T any] struct{ items []T } func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) } func (s *Stack[T]) Pop() (T, bool) { var zero T if len(s.items) == 0…
Generics·Q133·Medium
type Tree[K cmp.Ordered, V any] struct { root *node[K, V] size int } type node[K cmp.Ordered, V any] struct { key K val V left, right *node[K, V] } func (t *Tree[K, V])…
Generics·Q134·Medium
type Set[T comparable] map[T]struct{} func SetOf[T comparable](vs ...T) Set[T] { s := make(Set[T], len(vs)) for _, v := range vs { s[v] = struct{}{} } return s } func (s…
Generics·Q135·Hard
type Cache[K comparable, V any] struct { mu sync.Mutex items map[K]*entry[V] } type entry[V any] struct { once sync.Once val V err error } func NewCache[K comparable, V…
Generics·Q136·Medium
func Map[T, U any](xs []T, f func(T) U) []U { out := make([]U, len(xs)) for i, x := range xs { out[i] = f(x) } return out } func Filter[S ~[]E, E any](xs S, keep func(E)…
Generics·Q137·Medium
x/exp/constraints was the experimental home for common constraints: Signed , Unsigned , Integer , Float , Complex and Ordered . Only Ordered moved into the standard…
Generics·Q138·Medium
cmp (Go 1.21) provides Ordered , Compare(a, b) int (returns -1, 0 or +1) and Less(a, b) bool . Go 1.22 added Or(vals ...T) T , which returns the first non-zero argument…
Generics·Q139·Medium
slices : Sort , SortFunc , BinarySearch , Index , Contains , Insert , Delete , DeleteFunc , Compact , Equal , Clone , Grow , Reverse , Max , Min . Iterator helpers (Go…
Generics·Q140·Hard
iter.Seq[V] is a generic function type, func(yield func(V) bool) , and iter.Seq2[K, V] is the two-value form. for v := range seq calls seq with a compiler-generated…
Generics·Q141·Hard
Range-over-func iterators are push iterators: the sequence drives the loop. That makes it impossible to step through two sequences in lockstep with a single for .…
Generics·Q142·Hard
A type definition , type Set[T comparable] map[T]struct{} , creates a new, distinct named type that can have methods. A type alias , type A = B , is just another name…
Generics·Q143·Hard
No. Go generics are invariant . Each instantiation is a distinct named type, and there is no subtyping between instantiations, even when the type arguments are related…
Generics·Q144·Hard
func Nest[T any](n int) { if n > 0 { Nest[[]T](n - 1) } } func main() { Nest[int](3) } Result: compile error instantiation cycle: T instantiated as []T . Go instantiates…
Generics·Q145·Hard
type Pair[K comparable, V any] struct { Key K Val V } type Box[T any] struct{ v T } type MyInt int func main() { fmt.Printf("%T\n", Pair[string, int]{})…
Generics·Q146·Hard
func Merge[T any](ctx context.Context, chans ...<-chan T) <-chan T { out := make(chan T) var wg sync.WaitGroup for _, c := range chans { wg.Go(func() { // Go 1.25;…
Generics·Q147·Medium
Optional fields in API structs (JSON, protobuf, AWS SDK) are often pointers, and &42 or &"x" is not valid Go. Before generics every library shipped aws.String ,…
Goroutines & the Scheduler·Q148·Medium
A goroutine is a function running concurrently and scheduled by the Go runtime in user space. An OS thread is scheduled by the kernel. The main differences: Stack: a…
Goroutines & the Scheduler·Q149·Medium
The scheduler is built from three parts: G (goroutine): holds the goroutine's stack, saved registers ( gobuf ) and status ( _Grunnable , _Grunning , _Gwaiting ,…
Goroutines & the Scheduler·Q150·Hard
When the current goroutine blocks or gives up the CPU, the P calls schedule() → findRunnable() . It checks these sources, roughly in order: Every 61st scheduling tick,…
Goroutines & the Scheduler·Q151·Hard
package main import ( "fmt" "runtime" "sync" ) func main() { runtime.GOMAXPROCS(1) var wg sync.WaitGroup for i := range 5 { wg.Add(1) go func() { defer wg.Done()…
Goroutines & the Scheduler·Q152·Hard
Before Go 1.14, preemption was cooperative . sysmon marked a goroutine that had run for more than about 10 ms by setting its stack guard to stackPreempt . The goroutine…
Goroutines & the Scheduler·Q153·Hard
package main import ( "fmt" "runtime" "time" ) func main() { runtime.GOMAXPROCS(1) go func() { for { } }() time.Sleep(10 * time.Millisecond) fmt.Println("done") } Go…
Goroutines & the Scheduler·Q154·Hard
Every non-leaf function begins with a stack check : it compares SP with g.stackguard0 . If the frame will not fit, the function calls runtime.morestack . That function…
Goroutines & the Scheduler·Q155·Medium
GOMAXPROCS is the number of Ps, which is the maximum number of threads executing Go code at the same time. Threads blocked in syscalls or cgo do not count toward it. The…
Goroutines & the Scheduler·Q156·Medium
Usually no . This question often catches people who are used to Java or C thread pools. In Go, a goroutine blocked on network I/O does not hold a thread or a P. It parks…
Goroutines & the Scheduler·Q157·Hard
Before the syscall, the runtime calls entersyscall . The G moves to _Gsyscall , and its P moves to _Psyscall but stays attached to the M. The goal is to make fast…
Goroutines & the Scheduler·Q158·Hard
The netpoller is a runtime layer over the OS readiness APIs: epoll on Linux, kqueue on BSD/macOS, IOCP on Windows. Sockets are opened in non-blocking mode. When…
Goroutines & the Scheduler·Q159·Hard
sysmon is a runtime thread that runs without a P , so it keeps working even when every P is busy or stuck. It wakes up adaptively, every 20 µs to 10 ms, backing off when…
Goroutines & the Scheduler·Q160·Medium
runtime.Gosched() gives up the processor. The current G goes to the global run queue as runnable, and the P schedules something else. It does not sleep or block, and the…
Goroutines & the Scheduler·Q161·Hard
LockOSThread ties the calling goroutine to its current M. That goroutine then always runs on that thread, and no other goroutine runs on it . The call nests: you need…
Goroutines & the Scheduler·Q162·Medium
A goroutine leak is a goroutine that stays blocked forever, or runs forever, after its work no longer matters. It keeps its stack and everything that stack references,…
Goroutines & the Scheduler·Q163·Hard
In production: Export runtime.NumGoroutine() as a metric and alert when it grows steadily. Use net/http/pprof . /debug/pprof/goroutine?debug=1 groups stacks with counts,…
Goroutines & the Scheduler·Q164·Medium
The language sets no limit. In practice the limit is memory : at least about 2 KB of stack each, plus whatever each goroutine references. One million idle goroutines use…
Goroutines & the Scheduler·Q165·Medium
The Go team left out goroutine IDs on purpose. With IDs, people would build goroutine-local storage , which hides dependencies and breaks as soon as work moves to…
Goroutines & the Scheduler·Q166·Medium
package main import "fmt" func main() { go func() { defer fmt.Println("deferred") fmt.Println("in goroutine") }() fmt.Println("main done") } Most likely it prints only…
Goroutines & the Scheduler·Q167·Medium
A panic that no one recovers, in any goroutine, crashes the whole process and prints that goroutine's stack. recover works only inside a deferred function in the same…
Goroutines & the Scheduler·Q168·Medium
package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup var mu sync.Mutex sum := 0 for i := 0; i < 3; i++ { wg.Add(1) go func() { defer wg.Done()…
Goroutines & the Scheduler·Q169·Medium
The scheduler's checkdead function detects a deadlock only when no goroutine can make progress . That means there are no running Ms, and every remaining goroutine is…
Goroutines & the Scheduler·Q170·Medium
Concurrency is about how a program is structured: independent tasks whose execution can interleave. Parallelism is about execution: several tasks running at literally…
Goroutines & the Scheduler·Q171·Hard
The main G states in runtime2.go : _Gidle : just allocated. _Grunnable : in a run queue. _Grunning : owns an M and a P. _Gsyscall : in a syscall, owns an M but may lose…
Goroutines & the Scheduler·Q172·Hard
GODEBUG=schedtrace=1000 prints a line every second with gomaxprocs , idleprocs , threads , spinningthreads , runqueue (global) and the per-P local queue lengths [..] .…
Goroutines & the Scheduler·Q173·Medium
For CPU-bound work, only GOMAXPROCS goroutines can make progress at once. Adding more goroutines than that gives you no extra throughput. It does cost more: Switching…
Goroutines & the Scheduler·Q174·Hard
A cgo call switches from the goroutine's small, movable stack to the M's system (g0) stack , because C needs a large stack that does not move. The runtime treats the…
Goroutines & the Scheduler·Q175·Hard
Requirements: limit concurrency, stop the remaining work at the first error, wait for every goroutine to finish, and never block a sender forever. Without errgroup :…
Goroutines & the Scheduler·Q176·Medium
Yes. net/http runs one goroutine per connection , and each request on that connection is handled in that goroutine (HTTP/2 uses one goroutine per stream). This works…
Goroutines & the Scheduler·Q177·Hard
Since Go 1.14, timers live in a 4-ary heap per P . Before that, a single global timer goroutine handled them. The scheduler runs expired timers inside schedule() and…
Goroutines & the Scheduler·Q178·Hard
runtime.Goexit() ends the calling goroutine after running all its deferred calls. A recover in those deferred calls returns nil, because Goexit is not a panic. t.FailNow…
Goroutines & the Scheduler·Q179·Hard
package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup x := 1 wg.Add(2) go func(v int) { defer wg.Done() fmt.Println("arg:", v) }(x) go func() { defer…
Goroutines & the Scheduler·Q180·Hard
Two rules matter: The go statement that starts a goroutine is synchronized before the start of that goroutine. Writes the parent made before go are visible to the child.…
Goroutines & the Scheduler·Q181·Hard
That profile shows scheduler overhead , not your code. It usually means the program creates or wakes many tiny goroutines, so Ps keep running out of work, spin looking…
Goroutines & the Scheduler·Q182·Hard
synctest.Test(t, f) runs f in a new goroutine inside an isolated bubble . Goroutines started from it belong to the bubble, and the bubble has a fake clock that starts at…
Channels & select·Q183·Medium
An unbuffered channel ( make(chan T) ) is a rendezvous: a send blocks until a receiver is ready, and a receive blocks until a sender is ready. The handoff is…
Channels & select·Q184·Hard
A channel value is a pointer to a runtime.hchan struct allocated on the heap. Its main fields are: qcount , dataqsiz : number of elements currently queued and buffer…
Channels & select·Q185·Medium
Operation nil channel open channel closed channel send ch <- v blocks forever blocks until received/buffer space panic receive <-ch blocks forever blocks until value…
Channels & select·Q186·Medium
package main import "fmt" func main() { ch := make(chan int, 3) ch <- 1 ch <- 2 close(ch) for i := range 4 { v, ok := <-ch fmt.Println(i, v, ok) } } Output: 0 1 true 1 2…
Channels & select·Q187·Medium
v, ok := <-ch sets ok to false only when the channel is closed and drained. You need it when: you are inside a select and must notice closure so you can disable the case…
Channels & select·Q188·Medium
The rule: the sender closes, never the receiver , and only when there are no more sends. Closing is a broadcast message that says "no more values". A receiver closing…
Channels & select·Q189·Hard
First, restructure the code if you can, because multiple closers usually means ownership isn't clear. When you genuinely need a "stop" signal that several parties may…
Channels & select·Q190·Medium
If more than one case is ready, select picks one uniformly at random (pseudo-random). Source order gives no priority. The runtime ( selectgo ) shuffles the poll order…
Channels & select·Q191·Hard
Go has no built-in priority. The usual pattern is a non-blocking check of the high-priority channel first, followed by a blocking select over everything: for { // 1.…
Channels & select·Q192·Hard
Send and receive on a nil channel block forever, so a select case on a nil channel is never chosen . Setting a channel variable to nil therefore switches that case off…
Channels & select·Q193·Hard
package main import "fmt" func main() { var nilCh chan int closed := make(chan int) close(closed) counts := map[string]int{} for range 1000 { select { case <-nilCh:…
Channels & select·Q194·Medium
The runtime's checkdead triggers when every goroutine is blocked on something that no other goroutine can unblock (channel ops, select{} , sync primitives), and there…
Channels & select·Q195·Medium
package main import "fmt" func main() { ch := make(chan int) go func() { for v := range ch { fmt.Println(v) } }() ch <- 1 ch <- 2 close(ch) } It prints 1 and maybe 2 .…
Channels & select·Q196·Medium
for v := range ch receives until the channel is closed and drained , then exits. It reads one value per iteration (there is no index variable), and ranging over a nil…
Channels & select·Q197·Medium
chan<- T is send-only and <-chan T is receive-only. A bidirectional chan T converts implicitly to either one, but you can't convert back. The compiler rejects receiving…
Channels & select·Q198·Medium
// 1. time.After: simplest, fine for one-off selects select { case v := <-ch: use(v) case <-time.After(2 * time.Second): return errors.New("timeout") } // 2. Timer:…
Channels & select·Q199·Hard
for { select { case msg := <-msgs: handle(msg) case <-time.After(time.Minute): // new timer every iteration log.Println("idle") } } Before Go 1.23: every iteration…
Channels & select·Q200·Medium
A Ticker delivers ticks on a fixed schedule through one reusable channel. If the receiver falls behind, the ticker drops ticks instead of queuing them (the channel holds…
Channels & select·Q201·Medium
Use select with a default case. If no other case is ready, default runs right away. // Non-blocking send: drop if the consumer is behind (e.g. metrics, logs) select {…
Channels & select·Q202·Hard
package main import "fmt" func val(s string, v int) int { fmt.Println("eval", s); return v } func chn(s string, c chan int) chan int { fmt.Println("chan", s); return c }…
Channels & select·Q203·Medium
A buffered channel of capacity N acts as a counting semaphore: send to acquire, receive to release. func processAll(ctx context.Context, items []Item, limit int) error {…
Channels & select·Q204·Hard
type Result struct { Job int Out string Err error } func Pool(ctx context.Context, jobs []int, workers int) []Result { jobCh := make(chan int) resCh := make(chan Result)…
Channels & select·Q205·Hard
// LEAKS on timeout func fetch(url string) (string, error) { ch := make(chan string) // unbuffered go func() { ch <- slowGet(url) // blocks forever if nobody receives…
Channels & select·Q206·Medium
struct{} has size 0, so the channel buffer uses no memory for elements, and the type tells the reader that the value means nothing and the event is the point. A send…
Channels & select·Q207·Medium
package main import "fmt" func main() { var n chan int u := make(chan int) b := make(chan int, 5) b <- 1 b <- 2 <-b close(b) fmt.Println(len(n), cap(n), len(u), cap(u),…
Channels & select·Q208·Medium
The Go proverb says "Don't communicate by sharing memory; share memory by communicating", but the practical rule is: Channels are for passing ownership of data,…
Channels & select·Q209·Hard
A pipeline is a chain of stages. Each stage receives from an inbound channel, transforms the values, and sends on an outbound channel it owns and closes. The rules:…
Channels & select·Q210·Hard
ch := make(chan int, 1) close(ch) select { case ch <- 1: fmt.Println("sent") default: fmt.Println("default") } It panics with send on closed channel . It does not fall…
Channels & select·Q211·Hard
Yes. The Go memory model defines these synchronization rules for channels: A send on a channel is synchronized before the corresponding receive completes . Closing a…
Channels & select·Q212·Hard
// First successful result wins; the others are cancelled. func First[T any](ctx context.Context, fns ...func(context.Context) (T, error)) (T, error) { ctx, cancel :=…
Channels & select·Q213·Hard
package main import "fmt" func main() { reqs := make(chan chan int) go func() { n := 0 for reply := range reqs { n++ reply <- n } }() for range 3 { r := make(chan int)…
Channels & select·Q214·Medium
// Token bucket: burst of 5, refill 10/s func NewLimiter(ctx context.Context, rate time.Duration, burst int) <-chan struct{} { tokens := make(chan struct{}, burst) for…
Channels & select·Q215·Medium
Yes to all three. Channel types are comparable : two channel values are equal if they came from the same make call (the same hchan pointer) or are both nil. So channels…
Channels & select·Q216·Hard
func main() { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() jobs := make(chan Job, 100) var wg sync.WaitGroup for…
Channels & select·Q217·Hard
package main import "fmt" func main() { ch := make(chan int) go func() { for i := range 3 { ch <- i } close(ch) }() for { select { case v, ok := <-ch: if !ok { break }…
Channels & select·Q218·Hard
closechan sets the closed flag under the channel lock, removes every waiting sudog from both recvq and sendq , and makes all of those goroutines runnable: Blocked…
Channels & select·Q219·Hard
A channel's capacity is fixed at make time. The Go team has declined to add unbounded channels (the proposal is golang/go#20352) because a bounded buffer gives you…
Channels & select·Q220·Hard
A send copies the value ( elemsize bytes) into the buffer or straight to the receiver. That means: A large struct is copied on every send and again on every receive. For…
Concurrency Patterns & sync·Q221·Medium
RWMutex allows many concurrent readers or one writer. It pays off only when reads heavily outnumber writes and the critical section is long enough that letting readers…
Concurrency Patterns & sync·Q222·Hard
Normal mode: waiters queue in FIFO order, but a woken waiter does not get the lock handed to it. It has to compete with goroutines that are arriving right now, and those…
Concurrency Patterns & sync·Q223·Hard
No. Go mutexes are not reentrant and are not tied to a goroutine. If the same goroutine calls Lock twice, it deadlocks. One goroutine may also Unlock a mutex that a…
Concurrency Patterns & sync·Q224·Medium
type Counter struct { mu sync.Mutex n int } func (c Counter) Inc() { // value receiver c.mu.Lock() defer c.mu.Unlock() c.n++ } func main() { var c Counter var wg…
Concurrency Patterns & sync·Q225·Medium
The classic bug is calling Add inside the goroutine: // BUG: Wait may run before any Add, and return immediately for _, j := range jobs { go func() { wg.Add(1) defer…
Concurrency Patterns & sync·Q226·Medium
once.Do(f) runs f exactly once, even with concurrent callers. All callers block until f returns, and the completion of f happens-before any Do returns, so callers see…
Concurrency Patterns & sync·Q227·Hard
sync.Cond lets goroutines wait for a condition on shared state that a mutex protects. Wait does three things: it atomically unlocks c.L , suspends the goroutine, and…
Concurrency Patterns & sync·Q228·Hard
sync.Pool is a cache of temporary objects, sharded per P (processor), that reduces allocation pressure. Get tries, in order: the local P's private slot, the local P's…
Concurrency Patterns & sync·Q229·Medium
The docs name two cases where sync.Map is better: A key is written once and then read many times, as in a grow-only cache. Multiple goroutines read, write and overwrite…
Concurrency Patterns & sync·Q230·Medium
Go 1.19 added atomic.Int32 , Int64 , Uint32 , Uint64 , Uintptr , Bool and Pointer[T] . They are better than the function-based API for three reasons: No accidental…
Concurrency Patterns & sync·Q231·Hard
func StoreMax(a *atomic.Int64, v int64) { for { cur := a.Load() if v <= cur { return } if a.CompareAndSwap(cur, v) { return } // another goroutine changed it: reload and…
Concurrency Patterns & sync·Q232·Hard
The memory model says when a read in one goroutine is guaranteed to see a write made in another. If a write happens-before a read and no other write intervenes, the read…
Concurrency Patterns & sync·Q233·Hard
var done bool var msg string func setup() { msg = "hello" done = true } func main() { go setup() for !done { } fmt.Println(msg) } No output is guaranteed. This is a data…
Concurrency Patterns & sync·Q234·Medium
-race (for go test , go run and go build ) instruments every memory access and synchronization operation. It uses ThreadSanitizer's happens-before algorithm, based on…
Concurrency Patterns & sync·Q235·Medium
func main() { runtime.GOMAXPROCS(1) var n int var wg sync.WaitGroup for range 1000 { wg.Go(func() { n++ }) } wg.Wait() fmt.Println(n) } It will often print 1000 with one…
Concurrency Patterns & sync·Q236·Medium
func main() { var wg sync.WaitGroup for i := 0; i < 3; i++ { wg.Add(1) go func() { defer wg.Done() fmt.Print(i, " ") }() } wg.Wait() } Go 1.22 and later (when go.mod…
Concurrency Patterns & sync·Q237·Hard
func WorkerPool[In, Out any]( ctx context.Context, workers int, in <-chan In, fn func(context.Context, In) Out, ) <-chan Out { out := make(chan Out) var wg…
Concurrency Patterns & sync·Q238·Medium
Fan-out means several goroutines read from the same input channel to spread the work. Fan-in means merging several channels into one. func Merge[T any](ctx…
Concurrency Patterns & sync·Q239·Hard
Sending to or receiving from a nil channel blocks forever. Inside a select , a case on a nil channel is therefore never chosen. Setting a channel variable to nil is the…
Concurrency Patterns & sync·Q240·Hard
func gen(ctx context.Context, nums ...int) <-chan int { out := make(chan int) go func() { defer close(out) for _, n := range nums { select { case out <- n: case…
Concurrency Patterns & sync·Q241·Medium
func fastest(ctx context.Context, mirrors []string) string { ch := make(chan string) for _, m := range mirrors { go func() { ch <- fetch(ctx, m) }() } return <-ch } Only…
Concurrency Patterns & sync·Q242·Hard
The rule is that only a sender closes a channel, and only when no other sender can still send . Sending on a closed channel panics, closing twice panics, and a receiver…
Concurrency Patterns & sync·Q243·Medium
Buffered channel as a counting semaphore , which is idiomatic and has no dependencies: sem := make(chan struct{}, 10) // at most 10 in flight var wg sync.WaitGroup for…
Concurrency Patterns & sync·Q244·Hard
golang.org/x/sync/errgroup is a WaitGroup plus error propagation plus cancellation. g.Go(f) runs f in a goroutine. g.Wait() blocks until all functions return, then…
Concurrency Patterns & sync·Q245·Hard
The core ideas: stream the input instead of loading it, bound the number of goroutines, and apply backpressure through channels. func Process(ctx context.Context, r…
Concurrency Patterns & sync·Q246·Hard
Ticker: the simplest option is a fixed interval with no bursts. t := time.NewTicker(100 * time.Millisecond) // 10 rps defer t.Stop() for _, req := range reqs { select {…
Concurrency Patterns & sync·Q247·Hard
golang.org/x/sync/singleflight deduplicates concurrent calls for the same key. While one call for a key is in flight, later callers wait for it and share its result.…
Concurrency Patterns & sync·Q248·Hard
func main() { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() var workers sync.WaitGroup jobs := make(chan Job, 100)…
Concurrency Patterns & sync·Q249·Medium
WithCancelCause (1.20): cancel(err) records why the context was cancelled, and context.Cause(ctx) returns that error while ctx.Err() is still Canceled . It makes logs…
Concurrency Patterns & sync·Q250·Medium
for { select { case msg := <-msgs: handle(msg) case <-time.After(time.Minute): // new timer every iteration log.Println("idle") } } Before Go 1.23: every iteration…
Concurrency Patterns & sync·Q251·Medium
func main() { ch := make(chan int) ch <- 1 // no receiver fmt.Println(<-ch) } It prints fatal error: all goroutines are asleep - deadlock! . The send on an unbuffered…
Concurrency Patterns & sync·Q252·Hard
Naive double-checked locking reads a shared flag or pointer without synchronization: if !initialized { // racy read: may see true before the data writes are visible…
Concurrency Patterns & sync·Q253·Medium
The proverb is guidance, not a rule. Choose by the shape of the problem . Use channels when you are: transferring ownership of data (a producer hands work to a…
Concurrency Patterns & sync·Q254·Hard
Tests built on time.Sleep are slow and flaky. testing/synctest became generally available in Go 1.25. synctest.Test(t, f) runs f in an isolated "bubble": Time is…
Concurrency Patterns & sync·Q255·Hard
func main() { defer func() { if r := recover(); r != nil { fmt.Println("recovered:", r) } }() go func() { panic("boom") }() time.Sleep(time.Second) fmt.Println("done") }…
Concurrency Patterns & sync·Q256·Hard
CPUs keep memory coherent per cache line : 64 bytes on most x86-64 CPUs, 128 bytes on some arm64 and ppc64 chips. When two cores write different variables that sit on…
Concurrency Patterns & sync·Q257·Hard
GOMAXPROCS is the number of Ps, which is the maximum number of goroutines executing Go code at the same moment. Goroutines blocked in syscalls do not count against it.…
Concurrency Patterns & sync·Q258·Hard
A channel delivers each value to one receiver, so broadcasting needs a channel per subscriber. The hard parts are slow consumers, unsubscribing without a…
Context·Q259·Medium
context.Context carries three things across API boundaries and goroutines for the lifetime of one request or operation : a cancellation signal , an optional deadline ,…
Context·Q260·Hard
Each cancelable context ( *cancelCtx ) holds a mutex, a lazily created done channel, an err , a cause , and a children map[canceler]struct{} . When you derive a…
Context·Q261·Medium
Deriving a cancelable context registers the child in its parent's children map. WithTimeout / WithDeadline also start a time.Timer , and a custom parent may cause a…
Context·Q262·Medium
WithTimeout(parent, d) is exactly WithDeadline(parent, time.Now().Add(d)) . Use a timeout for a relative budget ("this call gets 2s") and a deadline when an absolute…
Context·Q263·Hard
func main() { parent, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() child, cancelChild := context.WithCancel(parent) defer…
Context·Q264·Medium
Err() returns nil while Done() is still open. Once it is closed, Err() returns exactly one of two sentinels: context.Canceled : someone called a cancel function, or a…
Context·Q265·Hard
WithCancelCause (Go 1.20) returns a CancelCauseFunc that takes an error saying why the context was canceled. ctx.Err() still returns only context.Canceled , which keeps…
Context·Q266·Hard
var errSlow = errors.New("payment provider slow") func main() { ctx, cancel := context.WithTimeoutCause(context.Background(), time.Hour, errSlow) cancel()…
Context·Q267·Medium
Value compares keys with == on the interface, so both the dynamic type and the value must match. If two packages both use the string "user" , they overwrite each other's…
Context·Q268·Medium
type ctxKey string func main() { ctx := context.WithValue(context.Background(), ctxKey("user"), "alice") ctx = context.WithValue(ctx, ctxKey("user"), "bob") child,…
Context·Q269·Hard
Every WithValue call wraps its parent in a valueCtx{Context; key, val any} that stores one pair . Value(k) is a linked-list walk: check this node's key, then move to the…
Context·Q270·Medium
The official guidance: use context values only for request-scoped data that crosses process and API boundaries , not for passing optional parameters to functions. Good…
Context·Q271·Medium
The context package docs say: "Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it." The reasons: Lifetime…
Context·Q272·Medium
Both return an empty context that is never canceled, has no deadline, and holds no values. They behave the same; the difference is intent , which static analysis tools…
Context·Q273·Hard
func AfterFunc(ctx Context, f func()) (stop func() bool) (Go 1.21) arranges for f to run in its own goroutine once ctx is done. If ctx is already done, f starts right…
Context·Q274·Hard
Turn the cancellation into something the blocking API does understand. For network connections that means setting a deadline in the past, which makes Read return at once…
Context·Q275·Hard
WithoutCancel(parent) (Go 1.21) returns a context that keeps the parent's values but is never canceled : Done() returns nil and Err() returns nil . Deadline() returns…
Context·Q276·Hard
func handler(w http.ResponseWriter, r *http.Request) { go func() { // sends an audit event to another service if err := sendAudit(r.Context(), r.URL.Path); err != nil {…
Context·Q277·Medium
For incoming server requests, r.Context() is canceled when any of these happens: the client's connection closes; the request is canceled (for example an HTTP/2…
Context·Q278·Medium
Attach the context with http.NewRequestWithContext (or req.WithContext ). Cancellation then applies to the whole exchange : dialing, TLS, writing the request, waiting…
Context·Q279·Hard
Use the *Context methods: QueryContext , ExecContext , QueryRowContext , BeginTx , PingContext , and Conn(ctx) . When the context is canceled: A call waiting for a pool…
Context·Q280·Hard
A common pattern wraps a legacy blocking function in a goroutine and uses select to wait for either the result or ctx.Done() . The trap: if the result channel is…
Context·Q281·Medium
For channel-driven loops, put ctx.Done() in the same select as the work channel. For CPU-bound loops that never block, check ctx.Err() regularly. Checking every N…
Context·Q282·Hard
errgroup.WithContext(parent) (from golang.org/x/sync/errgroup ) returns a group and a derived ctx . That ctx is canceled the first time a goroutine returns a non-nil…
Context·Q283·Hard
The standard library has no merge function, but WithCancelCause plus AfterFunc makes one cheap, without a dedicated watcher goroutine when both inputs are stdlib…
Context·Q284·Hard
Yes, any type that implements the four methods is a Context, and all methods must be safe for concurrent use. The most common custom context is not written from scratch:…
Context·Q285·Medium
A context does not travel over the network by itself; frameworks serialize parts of it. gRPC sends the remaining time in the grpc-timeout header. The server rebuilds a…
Context·Q286·Medium
signal.NotifyContext returns a context that is canceled when one of the listed signals arrives. It is the idiomatic root for a process's lifetime. func main() { ctx,…
Context·Q287·Medium
Techniques: t.Context() (Go 1.24): a per-test context that is canceled just before t.Cleanup functions run. It replaces context.Background() in tests, and goroutines…
Context·Q288·Medium
Yes. All Context methods and all cancel functions are safe to call from any number of goroutines. The rules: Done() returns the same channel on every call. For cancelCtx…
Context·Q289·Medium
Guidelines interviewers expect: Every function that does I/O, blocks, or might be slow takes ctx context.Context as its first parameter. Pure CPU helpers usually don't…
Context·Q290·Hard
func main() { ctx, cancel := context.WithCancel(context.Background()) cancel() done := make(chan struct{}) stop := context.AfterFunc(ctx, func() { fmt.Println("callback…
Context·Q291·Hard
var errShutdown = errors.New("shutting down") func main() { parent, cancel := context.WithCancelCause(context.Background()) detached := context.WithoutCancel(parent)…
Context·Q292·Hard
Since Go 1.23, iterators are plain functions that call yield . The loop body runs synchronously on the caller's goroutine , so there is no producer goroutine to leak.…
Context·Q293·Hard
Both packages in golang.org/x use a context to make waiting cancelable: (*semaphore.Weighted).Acquire(ctx, n) and (*rate.Limiter).Wait(ctx) block until a slot or token…
Error Handling & panics·Q294·Medium
In Go, error is an ordinary interface ( type error interface{ Error() string } ) returned as the last result. Failure paths are explicit in the signature and the control…
Error Handling & panics·Q295·Medium
a := errors.New("x") b := errors.New("x") fmt.Println(a == b) // false fmt.Println(a.Error() == b.Error()) // true type codeErr struct{ code int } func (e codeErr)…
Error Handling & panics·Q296·Medium
Both produce the same message text. %w also wraps : the returned error has an Unwrap() error method (or Unwrap() []error when there are several %w verbs, Go 1.20+), so…
Error Handling & panics·Q297·Medium
errors.Is(err, target) walks the error tree depth-first. At each node it returns true if the node == target (only when target's type is comparable) or if the node has an…
Error Handling & panics·Q298·Hard
errors.As(err, target any) bool finds the first error in the tree that is assignable to the type *target points at, stores it in *target , and returns true. A node can…
Error Handling & panics·Q299·Hard
errors.Join(errs ...error) (Go 1.20) returns an error that wraps every non-nil argument. It returns nil if all arguments are nil. Its message is the messages joined with…
Error Handling & panics·Q300·Medium
Sentinel ( var ErrNotFound = errors.New(...) ): a fixed value checked with errors.Is . It is simple and cheap, but it can't carry context, and it becomes part of your…
Error Handling & panics·Q301·Hard
A good custom error has structured fields, a message in lower case with no trailing punctuation, an Unwrap method if it wraps a cause, and usually a pointer receiver .…
Error Handling & panics·Q302·Hard
type MyErr struct{} func (*MyErr) Error() string { return "my err" } func do(fail bool) error { var p *MyErr // nil pointer if fail { p = &MyErr{} } return p // converts…
Error Handling & panics·Q303·Hard
== matches only the outermost error. As soon as someone wraps it with %w , the comparison fails. Use errors.Is , which walks the chain. The exceptions are documented…
Error Handling & panics·Q304·Hard
Wrap ( %w ) when callers need to inspect the cause and the cause is part of your stable contract. Don't wrap (use %v , or return your own error) when the cause is an…
Error Handling & panics·Q305·Medium
Panic when there is a programmer error or an impossible state that the caller can't reasonably handle: Violated invariants, such as an unreachable default in an…
Error Handling & panics·Q306·Hard
func helper() { if r := recover(); r != nil { fmt.Println("recovered:", r) } } func a() { defer helper(); panic("A") } // helper IS the deferred func func b() { defer…
Error Handling & panics·Q307·Hard
No. Panics are per goroutine. A panic unwinds only its own goroutine's stack. If nothing in that goroutine recovers, the whole process crashes, however many recovers sit…
Error Handling & panics·Q308·Hard
func main() { defer fmt.Println("1") defer func() { r := recover() fmt.Println("recovered", r) }() defer fmt.Println("3") fmt.Println(f()) panic("boom") } func f() (n…
Error Handling & panics·Q309·Medium
Use a named result and assign it inside a deferred function that calls recover . This is the only way a deferred function can change what the caller receives. func…
Error Handling & panics·Q310·Hard
Before Go 1.21, panic(nil) made recover() return nil , so code that tested if r := recover(); r != nil couldn't tell "no panic" from "panicked with nil" and swallowed…
Error Handling & panics·Q311·Hard
recover handles panics , both user panics and runtime-error panics (nil dereference, index out of range, nil map write, division by zero, failed type assertion, closing…
Error Handling & panics·Q312·Hard
Call Runs defers? Effect panic(v) Yes (current goroutine) Unwinds. Crashes with exit code 2 unless recovered. os.Exit(n) No Exits immediately with code n. Buffers aren't…
Error Handling & panics·Q313·Medium
Goroutines can't return values, so errors have to be passed back explicitly. golang.org/x/sync/errgroup is the standard tool. g.Go runs functions that return error .…
Error Handling & panics·Q314·Medium
Give each worker its own slot in a pre-sized slice. Each goroutine writes a different element, so there is no data race and no mutex. Then call errors.Join , which skips…
Error Handling & panics·Q315·Medium
The standard library leaves stacks out of errors on purpose: capturing them costs time, and well-written wrap messages usually give enough context. When you do need one:…
Error Handling & panics·Q316·Medium
Each error should be handled once. Handling means logging it, recovering from it (retry, fallback, default value), or turning it into a response. The alternative is to…
Error Handling & panics·Q317·Hard
For files opened for writing , Close (or the final flush) can be where the error shows up: buffered data, NFS, a full disk. defer f.Close() throws that error away, so…
Error Handling & panics·Q318·Medium
func parse(s string) error { var err error if s != "" { n, err := strconv.Atoi(s) // := declares a NEW err in this block if err == nil { fmt.Println("parsed", n) } }…
Error Handling & panics·Q319·Hard
It returns a non-nil error whose message is op: %!w(<nil>) . fmt.Errorf always returns a new error value, and it doesn't care whether the operand is nil. So an…
Error Handling & panics·Q320·Hard
ctx.Err() returns nil while the context is active. After it ends, it returns context.Canceled (from an explicit cancel) or context.DeadlineExceeded (from a timeout).…
Error Handling & panics·Q321·Medium
os.IsNotExist , os.IsExist and os.IsPermission were written before error wrapping existed. They unwrap only a fixed set of types ( *PathError , *LinkError ,…
Error Handling & panics·Q322·Medium
Instead of checking for a concrete type or sentinel, check whether the error implements a small interface that describes a behavior. The producer can then change its…
Error Handling & panics·Q323·Hard
http.Server recovers panics in each connection's goroutine. It logs the panic with a stack trace to ErrorLog and closes the connection, so the client gets a broken…
Error Handling & panics·Q324·Hard
A common senior-level design, inspired by Upspin and many internal Google and Uber codebases, is a single structured error type. It carries a machine-readable Kind (used…
Error Handling & panics·Q325·Hard
Read(p) can return n > 0 and a non-nil error in the same call, including io.EOF . The contract says callers should process the n bytes before looking at the error.…
Error Handling & panics·Q326·Medium
Any type with an Unwrap() error method is part of the chain. Without it, the wrapper is a dead end: errors.Is and errors.As stop at your type, and every caller checking…
Error Handling & panics·Q327·Hard
var ErrNotFound = errors.New("not found") type NotFoundError struct{ Name string } func (e *NotFoundError) Error() string { return e.Name + ": not found" } func (e…
Error Handling & panics·Q328·Hard
func main() { defer func() { fmt.Println("recovered:", recover()) }() defer func() { panic("second") }() panic("first") } Output: recovered: second . The new panic…
Error Handling & panics·Q329·Hard
With sync.Once , a panic in f still counts as "done". Do marks the Once as complete, the panic propagates to the first caller, and every later call returns immediately…
Error Handling & panics·Q330·Hard
Sentinel errors are created once at package init. Returning one is just copying an interface value, with no allocation. fmt.Errorf formats a string and allocates the…
Memory, GC & Runtime Internals·Q331·Medium
The language spec does not mention stack or heap. The compiler decides, using escape analysis . If it can prove a value is never referenced after its function returns,…
Memory, GC & Runtime Internals·Q332·Medium
Build with go build -gcflags='-m' ./... . Use -m -m for the reason chain behind each decision, and -gcflags='-m -l' to turn off inlining so the output is easier to…
Memory, GC & Runtime Internals·Q333·Hard
Returning or storing its address somewhere that outlives the frame: a global, a heap object, or a channel send of a pointer. Interface conversion , where a non-pointer…
Memory, GC & Runtime Internals·Q334·Hard
A goroutine starts with a small stack, historically 2 KB. Since Go 1.19 the runtime picks the starting size from the average stack usage it has observed. Every function…
Memory, GC & Runtime Internals·Q335·Hard
The allocator is derived from TCMalloc: Size classes : there are about 68 of them, covering objects up to 32 KB. Each request is rounded up to its class, so a 33-byte…
Memory, GC & Runtime Internals·Q336·Hard
Go's GC is concurrent, non-moving, non-generational, tri-color mark-sweep . Objects are in one of three sets: White : not yet seen. Any object still white at the end of…
Memory, GC & Runtime Internals·Q337·Hard
A write barrier is a small piece of code the compiler inserts around pointer writes into heap memory . It runs only while the GC is marking; otherwise it is skipped by a…
Memory, GC & Runtime Internals·Q338·Hard
Sweep termination (STW, microseconds) : finish sweeping the previous cycle, reach a safe point on every P, and enable the write barrier. Concurrent mark : the world…
Memory, GC & Runtime Internals·Q339·Medium
Neither. Go's GC does not move objects, so it never compacts, and it has no generations. Reasons given by the Go team: Escape analysis already keeps many short-lived…
Memory, GC & Runtime Internals·Q340·Medium
GOGC sets the heap growth target relative to the live data left after the last collection. Since Go 1.18 the formula also counts GC roots: heapGoal = liveHeap +…
Memory, GC & Runtime Internals·Q341·Hard
GOMEMLIMIT (Go 1.19+), or debug.SetMemoryLimit , sets a soft limit on all memory the Go runtime manages: heap, goroutine stacks and runtime metadata. It does not cover…
Memory, GC & Runtime Internals·Q342·Medium
gc 14 @2.104s 3%: 0.021+4.1+0.034 ms clock, 0.17+1.2/7.9/15+0.27 ms cpu, 48->52->21 MB, 50 MB goal, 0 MB stacks, 0 MB globals, 8 P gc 14 @2.104s 3% : the 14th cycle, 2.1…
Memory, GC & Runtime Internals·Q343·Hard
RSS includes more than live objects: Garbage not yet collected. With GOGC=100 the heap may reach about twice the live size. Idle spans that were freed but not yet…
Memory, GC & Runtime Internals·Q344·Medium
Measure first : go test -bench . -benchmem , then pprof -sample_index=alloc_space . Preallocate : make([]T, 0, n) and make(map[K]V, n) , and use strings.Builder.Grow .…
Memory, GC & Runtime Internals·Q345·Hard
sync.Pool is a concurrency-safe cache of temporary, interchangeable objects. Each P has its own local shard, so Get and Put take no lock in the common case. Objects can…
Memory, GC & Runtime Internals·Q346·Medium
In benchmarks, call b.ReportAllocs() or run with -benchmem to get B/op and allocs/op . Since Go 1.24, prefer b.Loop() . It resets the timer automatically and keeps the…
Memory, GC & Runtime Internals·Q347·Medium
In general, string(b) and []byte(s) copy the data, because strings are immutable and byte slices are not. The compiler removes the copy in patterns where it can prove…
Memory, GC & Runtime Internals·Q348·Medium
package main import ( "fmt" "unsafe" ) type A struct { a bool b int64 c bool } type B struct { b int64 a bool c bool } func main() { fmt.Println(unsafe.Sizeof(A{}),…
Memory, GC & Runtime Internals·Q349·Hard
Atomic alignment: on 32-bit platforms (386, ARM, 32-bit MIPS), 64-bit atomic operations need 8-byte alignment, but int64 fields are only guaranteed 4-byte alignment.…
Memory, GC & Runtime Internals·Q350·Hard
type T struct { x int64 z struct{} } type U struct { z struct{} x int64 } func main() { fmt.Println(unsafe.Sizeof(T{}), unsafe.Sizeof(U{}),…
Memory, GC & Runtime Internals·Q351·Hard
The unsafe package documents six valid patterns. Everything else is invalid, even if it happens to work today: Convert *T1 to unsafe.Pointer to *T2 , when T2 is no…
Memory, GC & Runtime Internals·Q352·Hard
There are two independent problems: No liveness. The GC does not treat a uintptr as a reference. If the uintptr is the last "reference", the object can be collected and…
Memory, GC & Runtime Internals·Q353·Hard
Since Go 1.20, use the dedicated functions and not the old header casts: // BytesToString: b must not be modified while the string is in use. func BytesToString(b…
Memory, GC & Runtime Internals·Q354·Hard
type Res struct{ name string } func main() { r := &Res{name: "db"} runtime.SetFinalizer(r, func(r *Res) { fmt.Println("finalized", r.name) }) r = nil runtime.GC()…
Memory, GC & Runtime Internals·Q355·Hard
Go 1.24 added: func AddCleanup[T, S any](ptr *T, cleanup func(S), arg S) Cleanup func (c Cleanup) Stop() Once ptr is unreachable, the runtime calls cleanup(arg) at some…
Memory, GC & Runtime Internals·Q356·Hard
Go 1.24 added the weak package. weak.Make(p) returns a weak.Pointer[T] that does not keep *p alive. wp.Value() returns the original pointer, or nil once the object has…
Memory, GC & Runtime Internals·Q357·Hard
The GC decides liveness from the point of last use , not from lexical scope. An object can therefore become unreachable, and its finalizer or cleanup can run, in the…
Memory, GC & Runtime Internals·Q358·Medium
func header(data []byte) []byte { return data[:4] } func main() { big := make([]byte, 10<<20) // 10 MiB h := header(big) big = nil runtime.GC() fmt.Println(len(h),…
Memory, GC & Runtime Internals·Q359·Medium
Reslicing only changes len . The elements past the new length stay in the backing array and still reference their objects, so the GC scans the whole array and keeps…
Memory, GC & Runtime Internals·Q360·Hard
No. delete and clear(m) free the slots for reuse, but the map's bucket and table storage never shrinks. If a map briefly held 10 million entries, it keeps that memory…
Memory, GC & Runtime Internals·Q361·Medium
A goroutine blocked forever is never collected, and neither is everything its stack references. Goroutine leaks are the most common real-world Go memory leak. // LEAK:…
Memory, GC & Runtime Internals·Q362·Medium
func consume(ch <-chan Event) { for { select { case e := <-ch: handle(e) case <-time.After(time.Minute): return // idle timeout } } } Before Go 1.23: every iteration…
Memory, GC & Runtime Internals·Q363·Medium
import _ "net/http/pprof" // registers /debug/pprof/* on DefaultServeMux func main() { go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }() // ... }…
Memory, GC & Runtime Internals·Q364·Medium
GOMAXPROCS is the number of Ps, which is the maximum number of threads running Go code at the same time. Before Go 1.25 it defaulted to the host's CPU count and ignored…
Memory, GC & Runtime Internals·Q365·Hard
type Stringer interface{ String() string } func main() { var ( s string sl []int m map[string]int ch chan int e any i Stringer f func() p *int )…
Memory, GC & Runtime Internals·Q366·Hard
Every index or slice expression is checked against the length at run time, and panics if out of range. The SSA backend's prove pass removes checks it can prove are…
Memory, GC & Runtime Internals·Q367·Hard
PGO (GA in Go 1.21) feeds a CPU profile from production back into the compiler. If a file named default.pgo is in the main package's directory, go build uses it…
Memory, GC & Runtime Internals·Q368·Hard
The GC and the scheduler both sometimes need to stop a goroutine at a point where its stack and registers can be described exactly: which slots hold live pointers. Those…
Performance, Profiling & Testing·Q369·Medium
Importing net/http/pprof for its side effect registers handlers under /debug/pprof/ on http.DefaultServeMux . The gotcha: if your public API server also uses…
Performance, Profiling & Testing·Q370·Medium
The CPU profiler is a sampling profiler: the runtime asks the OS for a timer signal (SIGPROF on Unix) at 100 Hz by default, and on each tick records the stack of the…
Performance, Profiling & Testing·Q371·Medium
The heap profile records allocation sites, sampled on average once per runtime.MemProfileRate bytes (default 512 KiB). It offers four sample types: inuse_space /…
Performance, Profiling & Testing·Q372·Medium
Symptom: runtime.NumGoroutine() (export it as a metric) grows monotonically along with memory. Diagnose with the goroutine profile: curl -s…
Performance, Profiling & Testing·Q373·Hard
Both are disabled by default because they add overhead. Block profile : where goroutines waited on synchronization primitives — channel send/recv, select , sync.Mutex ,…
Performance, Profiling & Testing·Q374·Hard
pprof aggregates samples into "where is time spent"; the execution tracer records a timeline of events : goroutine create/start/block/unblock, syscalls, network poller…
Performance, Profiling & Testing·Q375·Medium
b.Loop() returns true while the benchmark should keep iterating. It fixes three classic b.N mistakes: Setup cost : the timer is reset on the first call, so expensive…
Performance, Profiling & Testing·Q376·Hard
func square(x int) int { return x * x } func BenchmarkSquare(b *testing.B) { for i := 0; i < b.N; i++ { square(42) } } It typically reports something like 0.25 ns/op —…
Performance, Profiling & Testing·Q377·Medium
b.ReportAllocs() (or the -benchmem flag for all benchmarks) adds B/op and allocs/op columns. Allocations are often the best predictor of real-world cost because they…
Performance, Profiling & Testing·Q378·Medium
func TestParseDuration(t *testing.T) { tests := []struct { name string in string want time.Duration wantErr bool }{ {name: "seconds", in: "5s", want: 5 * time.Second},…
Performance, Profiling & Testing·Q379·Hard
func TestOrder(t *testing.T) { defer fmt.Println("defer") t.Cleanup(func() { fmt.Println("cleanup") }) for i := range 2 { t.Run(fmt.Sprint(i), func(t *testing.T) {…
Performance, Profiling & Testing·Q380·Medium
Parallel tests in a package run concurrently up to -parallel (default GOMAXPROCS ). Packages themselves run in parallel as separate processes ( -p ). Top-level parallel…
Performance, Profiling & Testing·Q381·Medium
defer : fine in a test without parallel subtests; runs when the function returns. t.Cleanup(fn) : runs after the test and all its subtests complete, in LIFO order.…
Performance, Profiling & Testing·Q382·Hard
Since Go 1.18, func FuzzXxx(f *testing.F) defines a coverage-guided fuzz target. f.Add supplies seed inputs; f.Fuzz takes a function whose first parameter is *testing.T…
Performance, Profiling & Testing·Q383·Hard
Testing code with timeouts, tickers, and background goroutines usually means real sleeps (slow and flaky) or injecting a fake clock everywhere. testing/synctest…
Performance, Profiling & Testing·Q384·Medium
Go's implicit interface satisfaction lets the consumer define a small interface describing only what it needs; production code passes the real type, tests pass a…
Performance, Profiling & Testing·Q385·Medium
Handlers : call the handler directly with httptest.NewRequest and httptest.NewRecorder — no network, fast. Clients : spin up httptest.NewServer (real loopback listener)…
Performance, Profiling & Testing·Q386·Medium
The toolchain rewrites source to increment counters per basic block. go test -coverprofile=cover.out ./... go tool cover -func=cover.out # per-function percentages go…
Performance, Profiling & Testing·Q387·Hard
PGO (GA in Go 1.21) feeds a CPU profile from production into the compiler so it optimizes hot paths more aggressively. The Go team reports typical gains of 2–14% CPU.…
Performance, Profiling & Testing·Q388·Hard
The compiler inlines functions whose body cost is under a budget (~ 80 AST nodes ). Inlining removes call overhead, but the bigger win is that it enables further…
Performance, Profiling & Testing·Q389·Hard
type Point struct{ X, Y int } func a() Point { p := Point{1, 2}; return p } // (1) func b() *Point { p := Point{1, 2}; return &p } // (2) func c() int { p := &Point{1,…
Performance, Profiling & Testing·Q390·Hard
Go is memory safe: every s[i] gets a runtime check that panics if i is out of range. The SSA backend's prove pass removes checks it can prove redundant. In tight loops…
Performance, Profiling & Testing·Q391·Hard
sync.Pool is a per-P cache of reusable temporary objects that reduces allocation rate and GC pressure for hot, short-lived objects (buffers, encoders). Semantics you…
Performance, Profiling & Testing·Q392·Medium
Strings are immutable, so s += x in a loop allocates a new string and copies everything each iteration: O(n²) bytes copied and n allocations. func concatPlus(parts…
Performance, Profiling & Testing·Q393·Hard
package main import ( "fmt" "strings" ) func main() { var a strings.Builder a.WriteString("hello") b := a b.WriteString(" world") fmt.Println(b.String()) } It panics :…
Performance, Profiling & Testing·Q394·Hard
Go's GC is a concurrent, non-generational, non-moving mark-sweep collector. Pacing: GOGC (default 100): the next GC triggers when the heap grows by GOGC% over the live…
Performance, Profiling & Testing·Q395·Medium
func main() { s := make([]int, 0, 2) a := append(s, 1) b := append(s, 2) fmt.Println(a[0], b[0], len(s), cap(s)) var grow []int prev := -1 for i := range 2000 { grow =…
Performance, Profiling & Testing·Q396·Hard
CPUs cache memory in 64-byte lines (128 on some ARM). If two cores write to different variables on the same cache line, the line ping-pongs between cores via the…
Performance, Profiling & Testing·Q397·Medium
Each field is aligned to its type's alignment (int64/pointers: 8 on 64-bit), and the struct's size is rounded up to its largest alignment. Poor ordering inserts padding.…
Performance, Profiling & Testing·Q398·Hard
A normal string(b) or []byte(s) copies because strings must be immutable. The compiler already avoids the copy in several cases: Map lookups: m[string(b)] (lookup only,…
Performance, Profiling & Testing·Q399·Medium
go test -race / go build -race instruments every memory access and uses ThreadSanitizer's happens-before (vector clock) algorithm. It reports when two goroutines access…
Performance, Profiling & Testing·Q400·Medium
Options for gating slow tests: testing.Short() : skip under go test -short . Build constraints: //go:build integration at the top of the file; run with go test…
Performance, Profiling & Testing·Q401·Medium
Functions named ExampleXxx in _test.go files serve as both documentation (rendered on pkg.go.dev next to the identifier) and tests. If the function ends with an //…
Performance, Profiling & Testing·Q402·Hard
A structured answer matters more than any one tool: Correlate metrics : CPU, RSS, goroutine count, GC cycles/sec and GC CPU fraction ( runtime/metrics ), request rate,…
Performance, Profiling & Testing·Q403·Hard
Benchmarks show allocs/op, but nobody reads benchmark output on every PR. For code that must stay allocation-free (encoders, loggers, request routing), lock it in with a…
Performance, Profiling & Testing·Q404·Hard
b.RunParallel(body) starts GOMAXPROCS × SetParallelism(p) goroutines (p defaults to 1) and splits the b.N iterations among them; each goroutine loops on pb.Next() . The…
Performance, Profiling & Testing·Q405·Hard
The old map was an array of buckets holding 8 entries each, with overflow buckets chained on collisions and incremental evacuation into a doubled array on growth. Go…
Performance, Profiling & Testing·Q406·Hard
The mark phase must scan every live object that contains pointers . Objects whose type has no pointers are allocated in "noscan" spans and are never scanned. So GC CPU…
Modules, Packages & Tooling·Q407·Medium
go.mod declares the module path, the minimum Go version ( go line), an optional toolchain , and minimum required versions of dependencies ( require ), plus replace ,…
Modules, Packages & Tooling·Q408·Hard
MVS builds the requirement graph starting from the main module. For each module path it picks the highest of the minimum versions that anything in the graph requires. It…
Modules, Packages & Tooling·Q409·Medium
The import compatibility rule says: if an old package and a new package have the same import path, the new one must be backward compatible with the old one. A major…
Modules, Packages & Tooling·Q410·Hard
Major branch (the common choice): on main, or on a v2 branch, change the go.mod line to module example.com/lib/v2 , update every internal import to the /v2 path, then…
Modules, Packages & Tooling·Q411·Medium
replace swaps the content of a module version for another version, another module path (a fork), or a local directory. Typical uses: testing a local fix before it goes…
Modules, Packages & Tooling·Q412·Hard
exclude is written by a consumer in the main module. It forbids one specific version. If something requires an excluded version, MVS moves up to the next higher…
Modules, Packages & Tooling·Q413·Medium
A pseudo-version stands for an untagged commit . It has the form vX.Y.Z-yyyymmddhhmmss-abcdefabcdef , made of a base version, the UTC commit time, and a 12-character…
Modules, Packages & Tooling·Q414·Medium
Workspaces (Go 1.18) let you build several local modules together as if they were all main modules, without editing any go.mod. They are the standard answer for "I'm…
Modules, Packages & Tooling·Q415·Medium
go mod vendor copies the packages needed to build and test the main module into vendor/ and writes vendor/modules.txt . Since Go 1.14, if vendor/ exists and go.mod says…
Modules, Packages & Tooling·Q416·Medium
The compiler enforces this rule: a package whose path contains an internal element can be imported only by code rooted at the parent of that internal directory . It is…
Modules, Packages & Tooling·Q417·Hard
By default GOPROXY=https://proxy.golang.org,direct and GOSUMDB=sum.golang.org . The public proxy cannot see private repos, and the checksum database would reject, or at…
Modules, Packages & Tooling·Q418·Hard
sum.golang.org is an append-only, Merkle-tree transparency log (Trillian) of go.sum lines for every public module version. The first time anyone in the world downloads…
Modules, Packages & Tooling·Q419·Hard
Since Go 1.21, go 1.22.0 is a strict minimum requirement (it used to be advisory). An older toolchain refuses to build the module, or downloads a newer one. The line…
Modules, Packages & Tooling·Q420·Hard
// go.mod: go 1.21 package main import "fmt" func main() { var fns []func() for i := 0; i < 3; i++ { fns = append(fns, func() { fmt.Print(i, " ") }) } for _, f := range…
Modules, Packages & Tooling·Q421·Medium
Before 1.24 the convention was a tools.go file with //go:build tools and blank imports, used to pin versions of developer tools (stringer, mockgen, sqlc) in go.mod. Go…
Modules, Packages & Tooling·Q422·Medium
Since Go 1.17/1.18 the jobs are separate: go get only changes dependency requirements in the current module's go.mod and go.sum. It no longer builds or installs…
Modules, Packages & Tooling·Q423·Medium
Build constraints decide whether a file is part of a package for a given build. There are two mechanisms. 1. //go:build expressions (Go 1.17+). These are boolean…
Modules, Packages & Tooling·Q424·Medium
Put a custom tag on the integration test files, then opt in when running tests: //go:build integration package store_test import "testing" func TestPostgresRoundTrip(t…
Modules, Packages & Tooling·Q425·Medium
go generate scans source files for //go:generate command args lines (no space after // ) and runs the commands with the package directory as the working directory. It is…
Modules, Packages & Tooling·Q426·Hard
"cgo is not Go." The costs: Call overhead : each Go-to-C call switches to the system stack and tells the scheduler. That is tens of nanoseconds, versus about 1 ns for a…
Modules, Packages & Tooling·Q427·Hard
The GC may move goroutine stacks and must be able to see every Go pointer. The rules, enforced at runtime when GODEBUG=cgocheck=1 (the default): Go may pass a Go pointer…
Modules, Packages & Tooling·Q428·Medium
The Go toolchain can cross-compile to every supported target: set GOOS / GOARCH (and GOARM / GOAMD64 for micro-architecture levels). cgo is disabled by default when…
Modules, Packages & Tooling·Q429·Hard
package main import "fmt" const commit = "none" var version = "dev" var built = defaultBuilt() func defaultBuilt() string { return "unknown" } func main() {…
Modules, Packages & Tooling·Q430·Medium
Since Go 1.18 every binary embeds its module path, dependency versions and hashes, build settings (GOOS, GOARCH, CGO_ENABLED, -tags , -ldflags ), and VCS information (…
Modules, Packages & Tooling·Q431·Medium
package main import ( "context" "fmt" "sync" "time" ) type Counter struct { mu sync.Mutex n int } func (c Counter) Inc() { c.mu.Lock(); c.n++; c.mu.Unlock() } // (1)…
Modules, Packages & Tooling·Q432·Medium
go vet is conservative and ships with the toolchain. staticcheck (Dominik Honnef) covers much more, with about 150 checks in several families: SA : bugs, e.g. SA4006…
Modules, Packages & Tooling·Q433·Medium
//go:embed (Go 1.16) compiles files into the binary at build time. The directive goes immediately above a package-level variable of type string , []byte , or embed.FS .…
Modules, Packages & Tooling·Q434·Hard
When a pattern names a directory , files whose names start with . or _ are excluded recursively. So //go:embed dist silently drops dist/.well-known/ , _app/ (SvelteKit…
Modules, Packages & Tooling·Q435·Hard
package main import "fmt" var a = b + 1 var b = f() func f() int { fmt.Println("f"); return 1 } func init() { fmt.Println("init1", a, b) } func init() {…
Modules, Packages & Tooling·Q436·Medium
The compiler rejects cycles ( import cycle not allowed ) because package initialization and compilation units must form a DAG. A cycle usually signals a design problem:…
Modules, Packages & Tooling·Q437·Medium
The commands used for dependency forensics: govulncheck ./... # is the vulnerable symbol actually reachable? go mod why -m golang.org/x/net # shortest import chain from…
Modules, Packages & Tooling·Q438·Hard
PGO became generally available in Go 1.21. The compiler uses a CPU profile from representative production load to make better decisions: inlining hot call sites more…
Modules, Packages & Tooling·Q439·Hard
// go.mod: go 1.20 (built with a Go 1.24 toolchain) package main import "fmt" func main() { defer func() { fmt.Printf("%T\n", recover()) }() panic(nil) } Answer: with go…
Modules, Packages & Tooling·Q440·Hard
Before 1.17 the go command had to load the go.mod of every module in the transitive graph, including modules that provide no package you actually build. From go 1.17…
Modules, Packages & Tooling·Q441·Hard
There are two separate caches: Module cache ( GOMODCACHE , default $GOPATH/pkg/mod ): extracted, read-only module source plus the downloaded zips and go.mod files in…
Modules, Packages & Tooling·Q442·Hard
//go:linkname localname importpath.name tells the compiler to use importpath.name as the object-file symbol for localname . It needs import _ "unsafe" . It comes in two…
Standard Library, HTTP & Systems Design in Go·Q443·Medium
http.Server.Serve runs an accept loop; for every accepted net.Conn it starts one goroutine ( go c.serve(ctx) ). With HTTP/1.1 keep-alive, that goroutine reads requests…
Standard Library, HTTP & Systems Design in Go·Q444·Medium
Since Go 1.22, patterns have the form [METHOD ][HOST]/[PATH] : "GET /items/{id}" — method + a single-segment wildcard, read via r.PathValue("id") . GET also matches HEAD…
Standard Library, HTTP & Systems Design in Go·Q445·Hard
Middleware is just func(http.Handler) http.Handler . To capture the status you wrap the ResponseWriter . The pitfall: the concrete writer implements optional interfaces…
Standard Library, HTTP & Systems Design in Go·Q446·Hard
The package-level helper creates an http.Server with zero timeouts , meaning a client can hold a connection forever (Slowloris: dribble headers one byte at a time and…
Standard Library, HTTP & Systems Design in Go·Q447·Hard
Pooling lives in http.Transport , not Client . The Transport keeps idle keep-alive connections keyed by scheme+host+proxy. Both are safe for concurrent use and should be…
Standard Library, HTTP & Systems Design in Go·Q448·Medium
The body is a stream over the underlying connection. Until it is closed, the Transport cannot reuse or free the connection — forgetting Close leaks a goroutine and a…
Standard Library, HTTP & Systems Design in Go·Q449·Medium
Server: each request carries r.Context() , which is canceled when the client closes the connection, when an HTTP/2 stream is reset, or when ServeHTTP returns. Pass it to…
Standard Library, HTTP & Systems Design in Go·Q450·Medium
func h(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello")) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) } The…
Standard Library, HTTP & Systems Design in Go·Q451·Hard
type Addr struct{ City string } type User struct { Name string `json:"name"` password string // unexported Age int `json:"age,omitempty"` Tags []string…
Standard Library, HTTP & Systems Design in Go·Q452·Hard
var m map[string]any json.Unmarshal([]byte(`{"id": 12345678901234567890, "n": 1}`), &m) fmt.Printf("%T %v\n", m["n"], m["id"]) _, ok := m["n"].(int) fmt.Println(ok)…
Standard Library, HTTP & Systems Design in Go·Q453·Hard
If MarshalJSON has a pointer receiver , only *T implements json.Marshaler . Marshaling a non-addressable T value (e.g. json.Marshal(t) , a value in a map, or a value…
Standard Library, HTTP & Systems Design in Go·Q454·Medium
Unmarshal works on a complete []byte and fails if there is trailing garbage. Decoder reads from an io.Reader , buffers internally, and can decode a stream of values…
Standard Library, HTTP & Systems Design in Go·Q455·Medium
type Resp struct { Items []int `json:"items"` Meta map[string]int `json:"meta"` Ptr *int `json:"ptr"` } var a []int b := []int{} x, _ := json.Marshal(Resp{Items: a}) y,…
Standard Library, HTTP & Systems Design in Go·Q456·Hard
*sql.DB is not a connection — it is a concurrency-safe pool , created once with sql.Open (which doesn't even connect; call PingContext ). Each query checks out a…
Standard Library, HTTP & Systems Design in Go·Q457·Medium
Transactions pin a single connection; all statements must use the *sql.Tx , not db (using db inside a tx runs on another connection and can deadlock with…
Standard Library, HTTP & Systems Design in Go·Q458·Hard
for { n, err := r.Read(buf) if err != nil { break } process(buf[:n]) } The contract: Read may return n > 0 and a non-nil error in the same call (including io.EOF ).…
Standard Library, HTTP & Systems Design in Go·Q459·Hard
The power of io.Reader / io.Writer is composition: io.TeeReader (read and copy to a writer), io.MultiWriter (fan-out writes), io.LimitReader , io.Pipe (connect a…
Standard Library, HTTP & Systems Design in Go·Q460·Medium
Scanner: the default max token size is 64 KB ( bufio.MaxScanTokenSize ). A longer line makes Scan() return false, and unless you check sc.Err() (which is…
Standard Library, HTTP & Systems Design in Go·Q461·Hard
Goal: on SIGINT/SIGTERM (Kubernetes sends SIGTERM, then SIGKILL after the grace period), stop accepting connections, let in-flight requests finish, stop workers, and…
Standard Library, HTTP & Systems Design in Go·Q462·Medium
log/slog (Go 1.21) separates the front-end *slog.Logger from a pluggable slog.Handler ( TextHandler , JSONHandler , or third-party). Records have a time, level, message…
Standard Library, HTTP & Systems Design in Go·Q463·Hard
t1 := time.Now() t2 := t1.Round(0) // strips monotonic reading fmt.Println(t1 == t2, t1.Equal(t2)) loc, _ := time.LoadLocation("Asia/Kolkata") t3 := t2.In(loc)…
Standard Library, HTTP & Systems Design in Go·Q464·Hard
A time.Ticker fires until you call Stop() ; always defer t.Stop() . Before Go 1.23, an unstopped Ticker/Timer was never garbage-collected, and time.After inside a hot…
Standard Library, HTTP & Systems Design in Go·Q465·Medium
retries := 3 // d := retries * time.Second // compile error: mismatched types int and time.Duration d := time.Duration(retries) * time.Second fmt.Println(d) const n = 3…
Standard Library, HTTP & Systems Design in Go·Q466·Hard
type Config struct { Port int host string } c := Config{Port: 80} v := reflect.ValueOf(c) fmt.Println(v.Field(0).CanSet()) p := reflect.ValueOf(&c).Elem()…
Standard Library, HTTP & Systems Design in Go·Q467·Hard
This tests walking struct fields, reading tags, handling pointers and Kinds, and producing errors with errors.Join . func Validate(s any) error { v := reflect.ValueOf(s)…
Standard Library, HTTP & Systems Design in Go·Q468·Hard
Token bucket: capacity b tokens, refilled at r per second; each request consumes one; allows bursts up to b . Compute tokens lazily from elapsed time — no background…
Standard Library, HTTP & Systems Design in Go·Q469·Hard
Classic O(1) LRU: a hash map from key to a node in a doubly linked list ( container/list ); move to front on access, evict from back when over capacity. TTL is checked…
Standard Library, HTTP & Systems Design in Go·Q470·Medium
When a hot key expires, hundreds of concurrent requests all miss and hit the database simultaneously (thundering herd). golang.org/x/sync/singleflight deduplicates…
Standard Library, HTTP & Systems Design in Go·Q471·Hard
Requirements: topics, concurrent publish, subscribe/unsubscribe at any time, and a publisher must never block on a slow consumer. Each subscriber gets a buffered channel…
Standard Library, HTTP & Systems Design in Go·Q472·Hard
golang.org/x/sync/errgroup is the idiomatic tool: WithContext cancels the shared context on the first error, SetLimit bounds concurrency, and Wait returns the first…
Standard Library, HTTP & Systems Design in Go·Q473·Medium
For handlers , use httptest.NewRecorder() and httptest.NewRequest — no network, fast, and you inspect the recorded status, headers and body. Route through your real mux…
Standard Library, HTTP & Systems Design in Go·Q474·Hard
SSE is a long-lived text/event-stream response where the server writes data: ...\n\n frames and flushes each one. Two things usually break it: (1) a middleware wrapper…
Standard Library, HTTP & Systems Design in Go·Q475·Hard
Retry only idempotent requests (GET, HEAD, PUT, DELETE, or POST with an idempotency key), and only on transient failures: network errors, 429, 502/503/504. A request…
Standard Library, HTTP & Systems Design in Go·Q476·Hard
httputil.ReverseProxy handles hop-by-hop header removal, streaming, trailers, HTTP/2, protocol upgrades (WebSockets) and error handling. Go 1.20 added the Rewrite hook,…
Standard Library, HTTP & Systems Design in Go·Q477·Hard
Tests using real time.Sleep are slow and flaky. testing/synctest (experimental in 1.24 behind GOEXPERIMENT=synctest , stable in Go 1.25 as synctest.Test ) runs a…
Tricky Output & Code-Review Puzzles·Q478·Medium
func main() { var wg sync.WaitGroup var ptrs []*int for i := 0; i < 3; i++ { ptrs = append(ptrs, &i) wg.Add(1) go func() { defer wg.Done() fmt.Print(i, " ") }() }…
Tricky Output & Code-Review Puzzles·Q479·Hard
for i := 0; i < 5; i++ { i++ fmt.Print(i, " ") } fmt.Println() for i := range 5 { i++ fmt.Print(i, " ") } The first prints 1 3 5 . The second prints 1 2 3 4 5 . In a…
Tricky Output & Code-Review Puzzles·Q480·Medium
func order() { for i := range 3 { defer fmt.Print(i, " ") } fmt.Print("end ") } func processAll(paths []string) error { for _, p := range paths { f, err := os.Open(p) if…
Tricky Output & Code-Review Puzzles·Q481·Medium
func main() { x := 1 defer fmt.Println("a", x) defer func() { fmt.Println("b", x) }() x = 2 } Output: b 2 a 1 The function value and arguments of a deferred call are…
Tricky Output & Code-Review Puzzles·Q482·Hard
func f() (r int) { defer func() { r *= 2 }() return 3 } func g() int { r := 3 defer func() { r *= 2 }() return r } func h() (r int) { defer func() { r *= 2 }() r = 1…
Tricky Output & Code-Review Puzzles·Q483·Hard
a := make([]int, 3, 10) b := append(a, 1) c := append(a, 2) fmt.Println(a, b, c) fmt.Println(len(a), len(b), cap(b)) Output: [0 0 0] [0 0 0 2] [0 0 0 2] 3 4 10 a has…
Tricky Output & Code-Review Puzzles·Q484·Medium
func modify(s []int) { s[0] = 99 s = append(s, 4) s[1] = 42 } func main() { x := []int{1, 2, 3} // len 3, cap 3 modify(x) fmt.Println(x) // ? y := make([]int, 3, 4) //…
Tricky Output & Code-Review Puzzles·Q485·Hard
func header(path string) ([]byte, error) { data, err := os.ReadFile(path) // e.g. 500 MB if err != nil { return nil, err } return data[:64], nil // keeps all 500 MB…
Tricky Output & Code-Review Puzzles·Q486·Hard
arr := [3]int{1, 2, 3} for i, v := range arr { if i == 0 { arr[1] = 100 } fmt.Print(v, " ") } fmt.Println(arr) sl := []int{1, 2, 3} for i, v := range sl { if i == 0 {…
Tricky Output & Code-Review Puzzles·Q487·Medium
type User struct { Name string Age int } users := []User{{"ann", 30}, {"bob", 40}} for _, u := range users { u.Age++ } fmt.Println(users) // [{ann 30} {bob 40}] u is a…
Tricky Output & Code-Review Puzzles·Q488·Hard
type MyErr struct{ msg string } func (e *MyErr) Error() string { return "myerr" } func do(fail bool) error { var p *MyErr if fail { p = &MyErr{"bad"} } return p // BUG }…
Tricky Output & Code-Review Puzzles·Q489·Medium
type Shape interface{ Area() float64 } type Square struct{ side float64 } func (s *Square) Area() float64 { return s.side * s.side } func main() { var s Shape =…
Tricky Output & Code-Review Puzzles·Q490·Hard
type T struct{ n int } func (t T) Val() { fmt.Println("val", t.n) } func (t *T) Ptr() { fmt.Println("ptr", t.n) } func main() { t := T{1} v := t.Val // method value p :=…
Tricky Output & Code-Review Puzzles·Q491·Medium
type Counter struct { mu sync.Mutex n int } func (c Counter) Inc() { // BUG: value receiver c.mu.Lock() defer c.mu.Unlock() c.n++ } func (c Counter) Value() int { return…
Tricky Output & Code-Review Puzzles·Q492·Hard
m := map[int]bool{1: true, 2: true, 3: true} for k := range m { m[k+10] = true } fmt.Println(len(m)) // ? for k := range m { if k > 5 { delete(m, k) // safe } } The…
Tricky Output & Code-Review Puzzles·Q493·Medium
type stat struct{ count int } m := map[string]stat{"a": {}} m["a"].count++ // compile error: cannot assign to struct field m["a"].count in map var nm map[string]int…
Tricky Output & Code-Review Puzzles·Q494·Medium
func parse(s string) (int, error) { var n int var err error if s != "" { n, err := strconv.Atoi(s) // := declares NEW n and err if err != nil { log.Println("inner:",…
Tricky Output & Code-Review Puzzles·Q495·Medium
func worker(id int, wg sync.WaitGroup) { // BUG 2: copied defer wg.Done() fmt.Println("worker", id) } func main() { var wg sync.WaitGroup for i := range 3 { go func() {…
Tricky Output & Code-Review Puzzles·Q496·Hard
func merge(a, b <-chan int, out chan<- int) { for { select { case v := <-a: out <- v case v := <-b: out <- v } } } A receive from a closed channel is always ready and…
Tricky Output & Code-Review Puzzles·Q497·Medium
a := make(chan int, 1) b := make(chan int, 1) a <- 1 b <- 2 select { case v := <-a: fmt.Println("a", v) case v := <-b: fmt.Println("b", v) } ticker := time.NewTicker(10…
Tricky Output & Code-Review Puzzles·Q498·Medium
This table comes up in almost every senior interview: Operation nil channel open channel closed channel send ch<-v blocks forever blocks/succeeds PANIC: send on closed…
Tricky Output & Code-Review Puzzles·Q499·Medium
// A ch := make(chan int) ch <- 1 // no receiver can ever run fmt.Println(<-ch) // B ch2 := make(chan int) go func() { for i := range 3 { ch2 <- i } // forgot close(ch2)…
Tricky Output & Code-Review Puzzles·Q500·Hard
var msg string func main() { c := make(chan int) // unbuffered go func() { msg = "hello" <-c // receive }() c <- 0 // send fmt.Println(msg) } Yes, with an unbuffered…
Tricky Output & Code-Review Puzzles·Q501·Hard
func fetchWithTimeout(ctx context.Context) (string, error) { ch := make(chan string) // BUG: unbuffered go func() { ch <- slowFetch() // blocks forever if nobody…
Tricky Output & Code-Review Puzzles·Q502·Hard
func handle() { if r := recover(); r != nil { fmt.Println("recovered:", r) } } func a() { defer handle(); panic("A") } // 1 func b() { defer func() { handle() }();…
Tricky Output & Code-Review Puzzles·Q503·Medium
func main() { defer func() { if r := recover(); r != nil { fmt.Println("recovered", r) } }() var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() var m…
Tricky Output & Code-Review Puzzles·Q504·Hard
func main() { defer func() { fmt.Println("recovered:", recover()) }() defer func() { fmt.Println("cleanup") panic("second") }() defer fmt.Println("first defer")…
Tricky Output & Code-Review Puzzles·Q505·Medium
var x int8 = 127 x++ fmt.Println(x) // ? var u uint8 = 0 u-- fmt.Println(u) // ? m := int8(-128) fmt.Println(-m) // ? fmt.Println(-7/2, -7%2) // ? // const big = 1 << 62…
Tricky Output & Code-Review Puzzles·Q506·Hard
fmt.Println(0.1+0.2 == 0.3) // true a, b := 0.1, 0.2 fmt.Println(a+b == 0.3) // false fmt.Println(a + b) // 0.30000000000000004 const huge = 1e1000 // fine as an untyped…
Tricky Output & Code-Review Puzzles·Q507·Medium
s := "héllo" fmt.Println(len(s)) // 6 fmt.Println(s[1]) // 195 fmt.Printf("%c %q\n", s[1], s[1:3]) // Ã "é" for i, r := range s { fmt.Print(i, ":", string(r), " ") //…
Tricky Output & Code-Review Puzzles·Q508·Hard
var a, b any = []int{1}, []int{1} fmt.Println(a == b) // panic: runtime error: comparing uncomparable type []int seen := map[any]bool{} seen[[]int{1}] = true // panic:…
Tricky Output & Code-Review Puzzles·Q509·Medium
var ErrNotFound = errors.New("not found") e1 := fmt.Errorf("get user: %v", ErrNotFound) e2 := fmt.Errorf("get user: %w", ErrNotFound) fmt.Println(e1) // get user: not…
Tricky Output & Code-Review Puzzles·Q510·Hard
func Count(n int) iter.Seq[int] { return func(yield func(int) bool) { for i := range n { yield(i) // BUG: ignores the return value } } } func main() { for x := range…
Tricky Output & Code-Review Puzzles·Q511·Medium
func main() { var n int var wg sync.WaitGroup for range 1000 { wg.Add(1) go func() { defer wg.Done() n++ // data race }() } wg.Wait() fmt.Println(n) // usually < 1000,…
Tricky Output & Code-Review Puzzles·Q512·Hard
s := []int{1, 2, 3, 4, 5} t := append(s[:1], s[3:]...) fmt.Println(t, s) u := []int{1, 2, 3, 4, 5} v := slices.Delete(u, 1, 3) fmt.Println(v, u) Output: [1 4 5] [1 4 5 4…
Tricky Output & Code-Review Puzzles·Q513·Hard
type Base struct{} func (Base) Name() string { return "base" } func (b Base) Greet() string { return "hi " + b.Name() } type Derived struct{ Base } func (Derived) Name()…
Tricky Output & Code-Review Puzzles·Q514·Hard
func describe(x any) string { switch v := x.(type) { case nil: return "nil" case int, int64: // return fmt.Sprint(v + 1) // compile error: v is any here return…
Tricky Output & Code-Review Puzzles·Q515·Hard
package main import "fmt" var ( a = c + b b = f("b") c = f("c") d = f("d") ) func f(s string) int { fmt.Print(s, " ") return len(s) } func init() { fmt.Print("init1 ") }…
Classic Concurrency Coding Problems·Q516·Medium
Channels: pass a "token" back and forth over two unbuffered channels. Only the goroutine holding the token may print, so the order is fixed. Each goroutine passes the…
Classic Concurrency Coding Problems·Q517·Medium
Pass a "ball" (a hit counter) between two players. Each player selects on both its input channel and ctx.Done() . The same applies to the send : a send that is not…
Classic Concurrency Coding Problems·Q518·Medium
Build a ring of channels. Goroutine i waits on chs[i] , prints, and then signals chs[(i+1)%3] . Main starts it by putting a token into chs[0] . This generalizes to any…
Classic Concurrency Coding Problems·Q519·Hard
The naive version has every philosopher take the left fork, then the right. If all five grab their left fork at the same time you get a circular wait, which is a…
Classic Concurrency Coding Problems·Q520·Medium
The naive from.mu.Lock(); to.mu.Lock() deadlocks like this. Goroutine 1 runs A->B and locks A. Goroutine 2 runs B->A and locks B. Now each waits for the lock the other…
Classic Concurrency Coding Problems·Q521·Hard
The Cond version uses a ring buffer and two condition variables that share one mutex. Put waits while the queue is full and Take waits while it is empty. Close…
Classic Concurrency Coding Problems·Q522·Hard
The hard part is making the barrier reusable . A fast goroutine can finish phase k and call Wait for phase k+1 before a slow waiter from phase k has even woken up. If…
Classic Concurrency Coding Problems·Q523·Medium
The future is a struct holding the result plus a done channel that is closed exactly once when the result is ready. The Go memory model guarantees that a close…
Classic Concurrency Coding Problems·Q524·Hard
A generator emits 2, 3, 4, ... For every prime p it finds, main adds a filter goroutine to the chain that drops multiples of p . The first value that reaches the end of…
Classic Concurrency Coding Problems·Q525·Hard
There are three concerns: Dedup: a mutex-guarded seen map. You must check and mark it in one critical section , before fetching. Otherwise two goroutines both see "not…
Classic Concurrency Coding Problems·Q526·Hard
Use a fixed pool of workers that read file paths from a channel. Each worker counts into its own private map , so the hot loop needs no locks and has no contention.…
Classic Concurrency Coding Problems·Q527·Hard
Debounce emits the last event only after a quiet period of d . Every new event restarts the timer. Throttle emits at most one event per interval, taking the first one…
Classic Concurrency Coding Problems·Q528·Hard
Hash each key to one of N shards. Each shard has its own RWMutex and a plain map, so operations on different shards never contend. Go 1.24's maphash.Comparable hashes…
Classic Concurrency Coding Problems·Q529·Hard
"Writer-preferring" means that once a writer is waiting, new readers must block, even though the current readers keep going. Otherwise a steady stream of readers starves…
Classic Concurrency Coding Problems·Q530·Hard
Each attempt gets a child context with a per-attempt timeout, and the overall deadline comes from the parent ctx . The attempt runs in a goroutine that writes into a…
Classic Concurrency Coding Problems·Q531·Hard
The supervisor starts the worker with a cancellable context and a beat callback. A timer is reset on every heartbeat. If the timer fires, the worker is considered hung:…
More Standard Library Essentials·Q532·Medium
You implement heap.Interface (which embeds sort.Interface , so Len , Less and Swap , plus Push(any) and Pop() any ). Then you call the package functions heap.Init ,…
More Standard Library Essentials·Q533·Medium
Stable: sort.SliceStable , sort.Stable and slices.SortStableFunc . Not stable: sort.Slice , sort.Sort , slices.Sort and slices.SortFunc , which all use pdqsort since Go…
More Standard Library Essentials·Q534·Hard
You write a layout by showing how the reference time 01/02 03:04:05PM '06 -0700 would look in your format: 1=month, 2=day, 3/15=hour, 4=minute, 5=second, 6=year, 7=zone.…
More Standard Library Essentials·Q535·Medium
math/rand and math/rand/v2 are fast pseudo-random generators whose output can be predicted . crypto/rand reads from the OS CSPRNG (getrandom, BCryptGenRandom and so on).…
More Standard Library Essentials·Q536·Hard
The two packages share the same syntax. text/template does no escaping . html/template parses the HTML around each action and works out its context : element body,…
More Standard Library Essentials·Q537·Medium
Always pass user values as arguments to QueryContext , ExecContext or QueryRowContext , and never build SQL with fmt.Sprintf or + . The driver sends the query and the…
More Standard Library Essentials·Q538·Hard
== and bytes.Equal return as soon as they hit the first byte that differs. By measuring response times over many requests, an attacker can recover a token or HMAC byte…
More Standard Library Essentials·Q539·Hard
Go's regexp uses RE2 syntax and automata-based matching (a Thompson NFA, a one-pass matcher and a bounded backtracker). It guarantees matching in O(m·n) time , linear in…
More Standard Library Essentials·Q540·Hard
exec.Command(name, args...) runs the program directly (execve or CreateProcess). No shell is involved, so ; , | , $() and globs inside arguments are just literal bytes.…
More Standard Library Essentials·Q541·Hard
The pattern: Call Accept in a loop. Start one goroutine per connection. Set deadlines on every read and write so that slow or idle clients cannot pin goroutines forever.…
More Standard Library Essentials·Q542·Medium
fs.FS (Go 1.16) is a minimal read-only interface: Open(name string) (fs.File, error) . Optional interfaces add capabilities: ReadDirFS , ReadFileFS , StatFS , SubFS and…
More Standard Library Essentials·Q543·Hard
os.OpenRoot(dir) returns an *os.Root . All of its operations ( Open , Create , OpenFile , Mkdir , Remove , Stat , Lstat , plus ReadFile , WriteFile , MkdirAll , Rename ,…
More Standard Library Essentials·Q544·Medium
You define flags ( flag.Int , flag.StringVar , flag.Func , flag.TextVar , flag.BoolFunc ), call flag.Parse() once in main , and read flag.Args() for the positional…
More Standard Library Essentials·Q545·Medium
strconv is type-specific and does not allocate for parsing. It returns precise errors and is several times faster than fmt.Sprintf("%d") or fmt.Sscan , which go through…
More Standard Library Essentials·Q546·Hard
encoding/binary: fixed-layout binary protocols and file formats (network headers, on-disk records, hashing inputs) where you control every byte. There is no schema and…
More Standard Library Essentials·Q547·Medium
The runtime receives OS signals and, for each signal you registered with signal.Notify(ch, sigs...) , forwards it to your channel instead of doing the default action…
Go Idioms, Design Patterns & Language Design·Q548·Medium
Functional options are variadic functions of type func(*T) (or func(*T) error ) applied to a value that already holds defaults. The constructor stays backward-compatible…
Go Idioms, Design Patterns & Language Design·Q549·Medium
Package-level var / init() runs eagerly and in a single thread before main , so it is thread-safe with no extra work. The cost is startup time and side effects (network,…
Go Idioms, Design Patterns & Language Design·Q550·Medium
Define a named integer type and a const block that uses iota . Go does not have closed enums: Status(42) compiles, and untyped constants convert implicitly, so…
Go Idioms, Design Patterns & Language Design·Q551·Hard
Inside the function, a variadic parameter xs ...int is a []int . A call like f(1, 2, 3) allocates a new slice. A call like f(s...) passes the caller's slice header as is…
Go Idioms, Design Patterns & Language Design·Q552·Medium
A closure captures variables , not values, by reference. It sees later writes, and its own writes are visible outside. If the closure outlives the stack frame (it is…
Go Idioms, Design Patterns & Language Design·Q553·Medium
Go's designers value code that is easy to read and maintain at scale, where every call site is unambiguous, over expressive power. Each missing feature has an idiomatic…
Go Idioms, Design Patterns & Language Design·Q554·Hard
Func values can only be compared to nil . f == g is a compile error ("func can only be compared to nil"), and map[func()]int is "invalid map key type". The reason:…
Go Idioms, Design Patterns & Language Design·Q555·Hard
No. The Go compiler does not guarantee tail-call elimination and in practice doesn't do it, partly to keep stack traces complete. Each recursive call uses a stack frame.…
Go Idioms, Design Patterns & Language Design·Q556·Medium
A common layout: cmd/<binary>/main.go holds thin mains that only do wiring. internal/ holds most of the code; the compiler enforces that only code rooted at internal's…
Go Idioms, Design Patterns & Language Design·Q557·Medium
Idiomatic DI in Go means constructors that accept interfaces or concrete dependencies as parameters , all wired explicitly in main . No container is needed. The…
Go Idioms, Design Patterns & Language Design·Q558·Medium
In Go these patterns usually collapse into small interfaces plus function types , with no class hierarchies. // Strategy: behavior chosen at runtime through an interface…
Go Idioms, Design Patterns & Language Design·Q559·Hard
A circuit breaker is a state machine. Closed : calls pass and failures are counted. Open : calls fail fast until a cooldown ends. Half-Open : a limited number of probe…
Go Idioms, Design Patterns & Language Design·Q560·Medium
_ is a write-only placeholder. Anything assigned to it is discarded, and it never creates a binding. import ( _ "embed" // needed for //go:embed on string/[]byte vars _…
Go Idioms, Design Patterns & Language Design·Q561·Medium
An anonymous struct is a struct type written inline without a name. Struct tags are raw string metadata on fields, read through reflection ( reflect.StructTag.Get ) by…
Go Idioms, Design Patterns & Language Design·Q562·Hard
The client sends an Idempotency-Key header (a UUID) with non-idempotent requests such as POST. The server atomically reserves the key, runs the operation once, stores…
Go Idioms, Design Patterns & Language Design·Q563·Medium
Concurrency: Go has goroutines on an M:N scheduler plus channels. Blocking-style code scales to 100k+ tasks without function coloring. Java 21+ virtual threads get…
Observability, Debugging & Production Operations·Q564·Medium
Delve is the Go debugger. It understands goroutines, the Go scheduler and Go types better than gdb does. The main entry points are: # build and debug the main package…
Observability, Debugging & Production Operations·Q565·Hard
GOTRACEBACK controls how much stack trace the runtime prints on an unrecovered panic or a fatal error: none : no goroutine traces. single (the default): only the…
Observability, Debugging & Production Operations·Q566·Medium
Use the github.com/prometheus/client_golang library: Counters only go up (requests, errors). Query them with rate() . Gauges go up and down (in-flight requests, queue…
Observability, Debugging & Production Operations·Q567·Hard
Setup takes three steps: Create a TracerProvider with an exporter (usually OTLP), a resource (service name) and a sampler. Register it globally along with a propagator.…
Observability, Debugging & Production Operations·Q568·Hard
RPC kinds. gRPC has four: Unary: one request, one response. Server streaming: one request, then stream.Send many times. Client streaming: Recv many times, then…
Observability, Debugging & Production Operations·Q569·Medium
The protobuf wire format identifies each field only by its field number and wire type , never by its name. Two rules follow from this: Backward compatibility (new code…
Observability, Debugging & Production Operations·Q570·Hard
Liveness asks "is this process stuck?". When it fails, Kubernetes restarts the container. It should be cheap and should not check dependencies. If the database goes down…
Observability, Debugging & Production Operations·Q571·Medium
Compile in a full Go image, then copy only the static binary into a tiny runtime image. CGO_ENABLED=0 produces a fully static binary with no libc dependency. Without it,…
Observability, Debugging & Production Operations·Q572·Medium
Load everything into one typed struct at startup. Use a clear order of precedence: defaults, then file, then environment, then flags. Validate the whole struct and fail…
Observability, Debugging & Production Operations·Q573·Hard
crypto/tls has safe defaults. Since Go 1.22 the default minimum version is TLS 1.2 for both clients and servers, and RSA key-exchange cipher suites are no longer offered…
Observability, Debugging & Production Operations·Q574·Hard
The standard library has no WebSocket server. Use github.com/gorilla/websocket or github.com/coder/websocket (formerly nhooyr, context-based and safe for concurrent…
Observability, Debugging & Production Operations·Q575·Hard
SetMaxStack(bytes) : the maximum size of a single goroutine's stack. The default is 1 GB on 64-bit and 250 MB on 32-bit. Going over it is a fatal "goroutine stack…
Observability, Debugging & Production Operations·Q576·Medium
runtime/metrics (Go 1.16+) is the stable, cheap API for runtime statistics. Unlike runtime.ReadMemStats , it does not stop the world. The Prometheus Go collector can…
Observability, Debugging & Production Operations·Q577·Hard
Start from the symptom: p99 latency is up but CPU is not saturated, so time is being spent waiting. Traces tell you which span is slow. Then work out which kind of…