Level: IntermediateInterview

Go Interview Questions: 150 Most Asked, with Full Answers

Updated 86 min read
Go Interview Questions featured image: basics to concurrency with answers

Go interview questions are now common in backend, cloud and DevOps hiring, because many teams build their APIs, tools and microservices in Go. This post gives you the 150 most asked questions, grouped from basic to advanced, and every single one now has a full answer in simple English, with code examples you can run.

This page is the complete, all-in-one list. For around 100 questions on each single topic, use the 29 topic posts in our Go topic-wise interview hub. For coding rounds, practise the Go coding interview programs, and for a full study plan, see all interview questions with a study path. All answers match current Go releases.

What Do Go Interview Questions Cover?

Go (also called Golang) is a simple, fast, compiled language made at Google. Also, it has built-in concurrency with goroutines and channels, a strong standard library, and quick build times.

Think of Go as a well-organised kitchen. There are only a few tools, but each one is sharp and easy to find. Interviewers check that you know each tool, and that you know when to use which one.

Most Go interview questions test six areas: basics and types, functions and methods, interfaces and errors, concurrency, the standard library and tooling, and real backend design. Senior rounds add performance, memory and architecture.

How to Use These Go Interview Questions

Do not try to memorise 150 answers in one go. Instead, use the list in three passes.

  1. First, read each question and try to answer it in two or three sentences before you read the answer.
  2. Next, run the code examples yourself and change them a little, because running code makes answers stick.
  3. Finally, mark the questions you missed and practise them out loud a few days later.

Every full program in this post was run, and its exact output is shown below it. Short snippets that need a server, a database, a test file or a newer Go version are marked as examples only. The table below shows how interview rounds usually use these questions.

RoundFocusQuestions
Phone screenBasics, types, slices, mapsQ1 to Q45
Technical roundInterfaces, errors, concurrencyQ46 to Q105
Senior roundTooling, performance, designQ106 to Q143
Scenario roundReal production problemsQ144 to Q150
Live codingWrite and explain a programHands-on section

How Go Code Runs

Before the questions, it helps to see how a Go program goes from source code to a running service. Interviewers often ask about this flow.

Go interview questions diagram showing source code, go build, a single binary and the Go runtime with goroutines
go build turns your code into one static binary, and the Go runtime inside it schedules goroutines and manages memory.

First, the go build command compiles your packages into one binary file. Then that binary includes the Go runtime, which runs your goroutines on a few operating system threads and cleans up memory with its garbage collector. So you can copy one file to a server and run it, with no extra installs.

Basic Go Interview Questions with Answers

These Go interview questions check that you know the core language. Freshers should be able to answer all of them, so read each answer slowly and run the small examples.

Q1. What is Go, and why did Google create it?

Go (also called Golang) is an open-source programming language made at Google by Robert Griesemer, Rob Pike and Ken Thompson. It was announced in 2009, and version 1.0 came out in 2012.

Google built Go because its big C++ and Java projects were slow to compile and hard to manage. So the team wanted a language that is simple to read, compiles in seconds, and handles many tasks at the same time. Today Go powers tools like Docker, Kubernetes and Terraform, and many backend APIs.

Q2. What are the main features of Go?

Go keeps a small set of features, but each one is useful. Here are the ones interviewers expect you to name.

  • Simple syntax: only 25 keywords, so code is easy to read.
  • Fast compilation: large projects build in seconds.
  • Static typing: the compiler catches type mistakes before the program runs.
  • Built-in concurrency: goroutines and channels make it easy to run work at the same time.
  • Garbage collection: Go frees unused memory for you.
  • Strong standard library: HTTP, JSON, testing, crypto and more are built in.
  • Single binary: your program and the runtime become one file that is easy to deploy.

Q3. Is Go compiled or interpreted?

Go is a compiled language. The go build command turns your source code into native machine code for your operating system and CPU. So there is no interpreter or virtual machine at run time, unlike Python or Java.

Even go run main.go compiles first. It just builds the program in a temporary folder and runs it straight away.

Q4. Is Go an object-oriented language?

The Go FAQ answers “yes and no”. Go has types and methods, so you can write in an object-oriented style. However, it has no classes and no inheritance.

Instead, Go uses three simple tools. Structs hold data, methods attach behaviour to a type, and interfaces describe what a type can do. You build bigger types by embedding smaller ones, which is called composition.

Q5. What is a package, and what is package main?

A package is a folder of .go files that belong together, such as fmt, strings or your own orders package. Every Go file starts with a package line. Packages help you organise code and reuse it.

package main is special. It tells Go to build an executable program instead of a library. A main package must have a func main(), which is where the program starts.

package main

import "fmt"

func main() {
    fmt.Println("Hello from package main")
}
Hello from package main

Q6. What is the difference between var and := ?

Both create variables, but they work in slightly different places.

Featurevar:=
Where it worksInside and outside functionsOnly inside functions
TypeCan be written or guessedAlways guessed from the value
Start valueOptionalRequired
Examplevar age int = 30age := 30

So use := for most local variables, because it is short. Use var for package-level variables, or when you want the zero value, such as var total int.

Q7. What are zero values in Go?

In Go, every variable always has a value. If you do not give one, Go sets a default called the zero value. This means you never read random garbage memory.

package main

import "fmt"

func main() {
    var count int
    var price float64
    var name string
    var active bool
    var scores []int
    var ages map[string]int

    fmt.Println(count, price, active)
    fmt.Printf("name=%q\n", name)
    fmt.Println(scores == nil, ages == nil)
}
0 0 false
name=""
true true

So numbers start at 0, strings at "", booleans at false, and pointers, slices, maps, channels, functions and interfaces at nil.

Q8. What are the basic data types in Go?

Go has a small set of built-in types. The table below groups them.

GroupTypes
Booleanbool
Signed integersint, int8, int16, int32, int64
Unsigned integersuint, uint8, uint16, uint32, uint64, uintptr
Floating pointfloat32, float64
Complexcomplex64, complex128
Textstring, byte (same as uint8), rune (same as int32)

On top of these, Go has composite types: arrays, slices, maps, structs, pointers, functions, interfaces and channels.

Q9. What is the difference between int, int32 and int64?

int32 is always 32 bits and int64 is always 64 bits, on every machine. int depends on the platform. It is 64 bits on 64-bit systems, which is almost every server today, and 32 bits on 32-bit systems.

Use int for counters, lengths and indexes, because built-ins like len return int. Use a fixed size such as int64 when the size matters, for example in file formats, network protocols or database columns. Also, Go never mixes them silently, so int plus int64 needs a conversion.

Q10. What is a rune, and how is it different from a byte?

A byte is an alias for uint8 and holds one raw byte. A rune is an alias for int32 and holds one Unicode character (a code point). Go strings are stored as UTF-8 bytes, and many characters, like Hindi letters or emojis, take more than one byte.

package main

import "fmt"

func main() {
    word := "héllo"
    fmt.Println("bytes:", len(word))         // é takes 2 bytes
    fmt.Println("runes:", len([]rune(word))) // 5 characters
    fmt.Println(word[1], string([]rune(word)[1]))
}
bytes: 6
runes: 5
195 é

So word[1] gives a single byte (195), while converting to []rune gives you whole characters.

Q11. What is a constant, and what does iota do?

A constant is a value fixed at compile time that never changes, such as const maxUsers = 100. Constants can be numbers, strings or booleans.

iota is a counter used inside a const block. It starts at 0 and goes up by one on each line. So it is handy for building enums.

package main

import "fmt"

type Weekday int

const (
    Sunday  Weekday = iota // 0
    Monday                 // 1
    Tuesday                // 2
)

const (
    _  = iota             // skip 0
    KB = 1 << (10 * iota) // 1 << 10
    MB                    // 1 << 20
)

func main() {
    fmt.Println(Sunday, Monday, Tuesday)
    fmt.Println(KB, MB)
}
0 1 2
1024 1048576

Q12. Does Go have implicit type conversion?

No. Go never converts between types for you, even between int and int64 or int and float64. You must convert on purpose, for example float64(count). This stops many hidden bugs, such as losing decimals without noticing.

The only exception is untyped constants. For example, var x float64 = 3 works, because the constant 3 has no fixed type until it is used.

Q13. How do you convert a string to an int and back?

Use the strconv package. strconv.Atoi turns a string into an int and returns an error if the text is not a number. strconv.Itoa turns an int into a string.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    age, err := strconv.Atoi("42")
    fmt.Println(age+1, err)

    _, err = strconv.Atoi("forty")
    fmt.Println(err)

    text := strconv.Itoa(2026)
    fmt.Println(text + "!")
}
43 <nil>
strconv.Atoi: parsing "forty": invalid syntax
2026!

Do not use string(65) to turn a number into text. It gives the character with that code, “A”, not “65”, and go vet warns about it.

Q14. What loops does Go have?

Go has only one loop keyword, for, but it covers every kind of loop. There is no while or do while.

package main

import "fmt"

func main() {
    for i := 0; i < 3; i++ { // classic three-part loop
        fmt.Print(i, " ")
    }
    fmt.Println()

    n := 1
    for n < 20 { // works like a while loop
        n *= 3
    }
    fmt.Println(n)

    for index, fruit := range []string{"apple", "mango"} { // range loop
        fmt.Println(index, fruit)
    }

    for i := range 3 { // range over an integer, Go 1.22+
        fmt.Print(i, " ")
    }
    fmt.Println()
}
0 1 2
27
0 apple
1 mango
0 1 2

A plain for { } with no condition runs forever until you break or return.

Q15. How does a switch statement work in Go, and does it fall through?

A Go switch runs the first matching case and then stops. It does not fall through to the next case, so you do not need break. If you really want to continue into the next case, you write fallthrough.

package main

import "fmt"

func grade(marks int) string {
    switch { // a switch with no value works like an if-else chain
    case marks >= 90:
        return "A"
    case marks >= 75:
        return "B"
    default:
        return "C"
    }
}

func main() {
    fmt.Println(grade(95), grade(80), grade(40))

    switch day := "sat"; day {
    case "sat", "sun": // one case can match many values
        fmt.Println("weekend")
    default:
        fmt.Println("weekday")
    }
}
A B C
weekend

Q16. What does the blank identifier _ do?

The blank identifier _ is a placeholder for a value you want to ignore. Go does not allow unused variables, so _ lets you skip what you do not need.

Here are common uses.

  • Skip a return value: _, err := strconv.Atoi(s).
  • Skip the index in a loop: for _, v := range items.
  • Import a package only for its side effects: import _ "github.com/lib/pq".
  • Check at compile time that a type meets an interface: var _ io.Reader = (*MyReader)(nil).

Q17. How do exported and unexported names work?

Go uses the first letter of a name to control visibility. If a name starts with a capital letter, such as Total or NewServer, it is exported and other packages can use it. If it starts with a small letter, such as total, it is unexported and stays private to its own package.

This rule applies to functions, types, variables, constants, struct fields and methods. So there is no public or private keyword in Go. Also, encoding/json can only see exported struct fields.

Q18. What does the init function do, and when does it run?

init is a special function that Go calls automatically before main. It takes no arguments and returns nothing, and you never call it yourself. A package can have several init functions, even in one file.

The order is simple. First, imported packages are set up. Then the package-level variables are set, then every init runs, and finally main starts.

package main

import "fmt"

var appName = setName()

func setName() string {
    fmt.Println("1. package variable set")
    return "shop"
}

func init() {
    fmt.Println("2. init runs")
}

func main() {
    fmt.Println("3. main runs for", appName)
}
1. package variable set
2. init runs
3. main runs for shop

Keep init small. Heavy work like database connections is better in main, where you can handle errors.

Q19. What is a Go module, and what are go.mod and go.sum?

A module is a collection of Go packages that are versioned together, usually one Git repository. You create one with go mod init github.com/you/project.

go.mod lists the module path, the Go version and the dependencies with their versions. go.sum stores checksums (hashes) of each dependency, so Go can check that the downloaded code was not changed. Commit both files to Git. Our Go dependencies post explains them step by step.

Q20. What do go run, go build and go install each do?

These three commands all compile your code, but they put the result in different places.

CommandWhat it doesUse it for
go run .Builds in a temp folder and runs itQuick tests while coding
go buildBuilds a binary in the current folderMaking a file to deploy
go installBuilds and puts the binary in $GOPATH/binInstalling command-line tools

For example, go install golang.org/x/tools/cmd/goimports@latest installs a tool you can run from anywhere.

Q21. What is the difference between new and make?

Both are built-in functions, but they do different jobs. new(T) works for any type. It creates a zero value and returns a pointer, *T. make works only for slices, maps and channels. It sets up their inner structure and returns the value itself, not a pointer.

package main

import "fmt"

func main() {
    p := new(int) // *int pointing to 0
    *p = 7
    fmt.Println(*p)

    nums := make([]int, 2, 5) // slice: length 2, capacity 5
    ages := make(map[string]int)
    ages["Ravi"] = 30
    ch := make(chan string, 1) // buffered channel

    fmt.Println(len(nums), cap(nums), ages, cap(ch))
}
7
2 5 map[Ravi:30] 1

So if you used new on a map, you would get a pointer to a nil map, and writing to it would panic.

Q22. What is variable shadowing, and why can it cause bugs?

Shadowing happens when you declare a new variable with the same name in an inner block. The inner one hides the outer one, so changes inside do not reach the outer variable.

package main

import "fmt"

func main() {
    total := 10
    if true {
        total := 99 // new variable, hides the outer total
        fmt.Println("inside:", total)
    }
    fmt.Println("outside:", total) // still 10
}
inside: 99
outside: 10

The classic bug is err inside an if block with :=, so the outer err stays nil. To catch this, read your := lines carefully and use linters such as go vet with the shadow analyzer.

Q23. How do labels work with break and continue in nested loops?

A plain break only stops the innermost loop. To stop or skip an outer loop, put a label before it and use break Label or continue Label.

package main

import "fmt"

func main() {
    grid := [][]int{{1, 2, 3}, {4, -1, 6}, {7, 8, 9}}

Search:
    for row, line := range grid {
        for col, value := range line {
            if value < 0 {
                fmt.Println("negative found at", row, col)
                break Search // leave both loops at once
            }
        }
    }
    fmt.Println("done")
}
negative found at 1 1
done

Q24. What changed for loop variables in Go 1.22?

Before Go 1.22, a for loop used one variable for all passes. So goroutines and closures created in the loop often saw only the last value. Since Go 1.22, each pass gets its own new variable.

package main

import "fmt"

func main() {
    var printers []func()
    for i := 1; i <= 3; i++ {
        printers = append(printers, func() { fmt.Print(i, " ") })
    }
    for _, p := range printers {
        p()
    }
    fmt.Println()
}
1 2 3

With Go 1.21 or older, this program printed 4 4 4. The new rule applies when your go.mod says go 1.22 or later.

Q25. What do the go and toolchain lines in go.mod mean?

The go line, such as go 1.24, sets the minimum Go version needed to build the module. It also turns on language features from that version, such as the new loop variable rule. Since Go 1.21, an older Go toolchain refuses to build a module that needs a newer version.

The optional toolchain line, such as toolchain go1.25.3, says which Go toolchain to use. If your installed Go is older, the go command can download the right one automatically.

Slices, Maps and Strings Go Interview Questions with Answers

Data structure questions come up in every round. So prepare these Go interview questions with small programs, because many of them are “what does this print?” questions.

Q26. What is the difference between an array and a slice?

An array has a fixed length that is part of its type. So [3]int and [4]int are different types, and an array can never grow. A slice is a flexible view over an array. It has a length and a capacity, and it can grow with append.

FeatureArraySlice
LengthFixed, part of the typeCan change
Example type[5]int[]int
Passed to a functionWhole array is copiedSmall header copied, data shared
Zero valueArray of zero valuesnil
Used in real codeRarelyAlmost always

So in real Go code, you use slices almost every time. Arrays are mostly used for fixed things, such as a 32-byte hash.

Q27. What are the length and capacity of a slice?

The length, len(s), is how many items the slice holds right now. The capacity, cap(s), is how many items fit in the underlying array, counting from the start of the slice. You can only read or write up to the length, but append can use the spare capacity without new memory.

package main

import "fmt"

func main() {
    s := make([]int, 2, 5)
    fmt.Println(len(s), cap(s), s)

    s = append(s, 7)
    fmt.Println(len(s), cap(s), s)

    t := s[1:2] // capacity counts from index 1 to the end of the array
    fmt.Println(len(t), cap(t), t)
}
2 5 [0 0]
3 5 [0 0 7]
1 4 [0]

Q28. What happens when append needs more capacity?

If the slice has spare capacity, append writes into the same array. If not, Go makes a new, bigger array, copies the old items into it and returns a slice that points to the new array. So the old and new slices stop sharing data.

The new size is roughly double for small slices and grows by a smaller factor for big ones. The exact rule can change between Go versions, so do not depend on it. Always use the result, as in s = append(s, x).

package main

import "fmt"

func main() {
    a := []int{1, 2, 3} // len 3, cap 3, no spare room
    b := append(a, 4)   // needs a new array
    b[0] = 100
    fmt.Println(a, b) // a is not changed
    fmt.Println(cap(b) > cap(a))
}
[1 2 3] [100 2 3 4]
true

Q29. Why can two slices change each other’s data?

A slice does not hold the data itself. It holds a pointer to an array, a length and a capacity. When you slice a slice, or copy a slice variable, both point to the same array. So writing through one changes what the other sees.

package main

import "fmt"

func main() {
    marks := []int{50, 60, 70, 80}
    top := marks[2:] // shares the same array
    top[0] = 99
    fmt.Println(marks, top)
}
[50 60 99 80] [99 80]

This also happens when you pass a slice to a function. The function can change the items, but if it appends past the capacity, the caller will not see the new items.

Q30. How do you copy a slice safely?

Use the built-in copy function into a new slice of the right length, or use slices.Clone (Go 1.21+). Both give you a separate array, so changes do not leak back.

package main

import (
    "fmt"
    "slices"
)

func main() {
    original := []string{"go", "rust", "java"}

    copyA := make([]string, len(original))
    n := copy(copyA, original) // returns how many items were copied
    copyB := slices.Clone(original)

    copyA[0] = "GO"
    copyB[1] = "RUST"
    fmt.Println(n, original, copyA, copyB)
}
3 [go rust java] [GO rust java] [go RUST java]

Q31. What is a nil slice, and how is it different from an empty slice?

A nil slice, var s []int, has no underlying array, and s == nil is true. An empty slice, s := []int{}, has an array with zero items, so s == nil is false. Both have length 0, and you can range over and append to both.

The main difference shows up in JSON. A nil slice encodes as null, and an empty slice encodes as [].

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var nilSlice []int
    emptySlice := []int{}

    fmt.Println(nilSlice == nil, emptySlice == nil, len(nilSlice), len(emptySlice))

    a, _ := json.Marshal(nilSlice)
    b, _ := json.Marshal(emptySlice)
    fmt.Println(string(a), string(b))
}
true false 0 0
null []

Q32. How do you remove an item from a slice?

Since Go 1.21, the easiest way is slices.Delete(s, i, i+1), which removes the item at index i and keeps the order. Before that, people wrote append(s[:i], s[i+1:]...). If order does not matter, you can move the last item into the gap, which is faster.

package main

import (
    "fmt"
    "slices"
)

func main() {
    cities := []string{"Pune", "Delhi", "Mumbai", "Goa"}
    cities = slices.Delete(cities, 1, 2) // remove "Delhi"
    fmt.Println(cities)

    nums := []int{10, 20, 30, 40}
    i := 0
    nums[i] = nums[len(nums)-1] // fast remove: order not kept
    nums = nums[:len(nums)-1]
    fmt.Println(nums)
}
[Pune Mumbai Goa]
[40 20 30]

Q33. What is a map, and what types can be map keys?

A map stores key-value pairs and finds a value by its key very fast, like a phone book. You create one with make(map[string]int) or a literal like map[string]int{"a": 1}.

A key type must be comparable with ==. So strings, numbers, booleans, pointers, channels, arrays and structs made of comparable fields can be keys. Slices, maps and functions cannot be keys, because they are not comparable.

Q34. Is map iteration order fixed?

No. The order of a range loop over a map is not defined, and Go randomises it on purpose so you do not depend on it. If you need a fixed order, collect the keys, sort them and then loop.

package main

import (
    "fmt"
    "maps"
    "slices"
)

func main() {
    stock := map[string]int{"pen": 5, "book": 2, "bag": 9}

    keys := slices.Sorted(maps.Keys(stock)) // Go 1.23+
    for _, k := range keys {
        fmt.Println(k, stock[k])
    }
}
bag 9
book 2
pen 5

The fmt package prints maps in sorted key order, which makes test output stable. However, a range loop never does.

Q35. What happens if you write to a nil map?

Reading from a nil map is safe and returns the zero value. However, writing to a nil map causes a panic: assignment to entry in nil map. So always create the map with make or a literal before you add keys.

var counts map[string]int // nil map
fmt.Println(counts["go"]) // 0, reading is fine
counts["go"] = 1          // panic: assignment to entry in nil map

counts = make(map[string]int) // fix: create it first
counts["go"] = 1              // works

Q36. How do you check if a key exists in a map?

Use the “comma ok” form. The second value is true if the key is present. This matters because a missing key returns the zero value, which might look like a real value.

package main

import "fmt"

func main() {
    scores := map[string]int{"Asha": 0, "Ravi": 85}

    if score, ok := scores["Asha"]; ok {
        fmt.Println("Asha found with", score)
    }
    _, ok := scores["Meena"]
    fmt.Println("Meena found:", ok)

    delete(scores, "Ravi") // deleting a key
    fmt.Println(len(scores))
}
Asha found with 0
Meena found: false
1

Q37. Are maps safe for use by many goroutines?

No. Reading from many goroutines at once is fine, but if any goroutine writes while others read or write, it is a data race. The Go runtime often detects this and crashes with fatal error: concurrent map writes.

There are three common fixes. Protect the map with a sync.Mutex, use a sync.RWMutex when reads are much more common than writes, or use sync.Map for special cases such as a cache where keys are written once and read many times.

Q38. Are strings mutable in Go?

No. Strings are immutable, so you cannot change a byte in place. s[0] = 'H' does not compile. To change text, you build a new string, or convert to []byte or []rune, edit it and convert back.

package main

import "fmt"

func main() {
    name := "golang"
    b := []byte(name) // a copy you can change
    b[0] = 'G'
    fmt.Println(string(b), name)
}
Golang golang

Because strings are immutable, they are safe to share between goroutines, and substrings can share memory without copying.

Q39. How do you loop over a string by characters?

Use range. It decodes UTF-8 for you and gives the byte index and the rune (character) on each pass. A normal index loop, for i := 0; i < len(s); i++, goes byte by byte, which breaks non-English text.

package main

import "fmt"

func main() {
    for index, char := range "नमस्ते" {
        fmt.Printf("%d:%c ", index, char)
    }
    fmt.Println()
}
0:न 3:म 6:स 9:् 12:त 15:े

So the index jumps by 3, because each of these Hindi characters takes 3 bytes in UTF-8.

Q40. How do you build a long string efficiently?

Use strings.Builder. Adding strings with + in a loop creates a new string every time, which wastes memory and time. A builder grows one buffer and makes the final string once.

package main

import (
    "fmt"
    "strings"
)

func main() {
    var sb strings.Builder
    for i := 1; i <= 5; i++ {
        fmt.Fprintf(&sb, "item%d,", i)
    }
    result := strings.TrimSuffix(sb.String(), ",")
    fmt.Println(result)

    fmt.Println(strings.Join([]string{"a", "b", "c"}, "-")) // for a ready slice
}
item1,item2,item3,item4,item5
a-b-c

If you know the final size, call sb.Grow(n) first to avoid extra copies.

Q41. What do the slices and maps packages in the standard library give you?

These generic packages were added in Go 1.21. They give you ready-made helpers, so you do not write the same loops again and again.

PackageUseful functions
slicesSort, SortFunc, Contains, Index, Max, Min, Reverse, Equal, Clone, Delete, Insert, Compact
mapsClone, Copy, Equal, DeleteFunc, and since Go 1.23 Keys, Values, All (iterators)
package main

import (
    "fmt"
    "slices"
)

func main() {
    nums := []int{40, 10, 30, 10}
    slices.Sort(nums)
    fmt.Println(nums, slices.Contains(nums, 30), slices.Max(nums))
    fmt.Println(slices.Compact(nums)) // removes repeated neighbours
}
[10 10 30 40] true 40
[10 30 40]

Q42. What do the built-in min, max and clear functions do?

These built-ins came in Go 1.21. min and max return the smallest or largest of their arguments, for any ordered type. clear empties a map, or sets every item of a slice to its zero value.

package main

import "fmt"

func main() {
    fmt.Println(min(4, 2, 8), max(3.5, 1.2), min("pear", "apple"))

    cart := map[string]int{"pen": 2, "book": 1}
    clear(cart)
    fmt.Println(len(cart))

    seats := []int{1, 2, 3}
    clear(seats)
    fmt.Println(seats, len(seats))
}
2 3.5 apple
0
[0 0 0] 3

So clear on a slice keeps the length. It only resets the values.

Q43. How do you sort a slice of structs by a field?

Use slices.SortFunc with a compare function, or the older sort.Slice. The cmp.Compare helper returns -1, 0 or 1, which is exactly what SortFunc needs.

package main

import (
    "cmp"
    "fmt"
    "slices"
)

type Employee struct {
    Name   string
    Salary int
}

func main() {
    staff := []Employee{{"Ravi", 50000}, {"Asha", 70000}, {"Meena", 60000}}

    slices.SortFunc(staff, func(a, b Employee) int {
        return cmp.Compare(b.Salary, a.Salary) // highest salary first
    })
    for _, e := range staff {
        fmt.Println(e.Name, e.Salary)
    }
}
Asha 70000
Meena 60000
Ravi 50000

Use slices.SortStableFunc when items with equal values must keep their original order.

Q44. Is it possible to compare two slices or two maps with ==?

No. Slices and maps can only be compared with nil. Writing a == b for two slices does not compile. To compare contents, use slices.Equal and maps.Equal, or reflect.DeepEqual for nested data such as in tests.

package main

import (
    "fmt"
    "maps"
    "slices"
)

func main() {
    fmt.Println(slices.Equal([]int{1, 2}, []int{1, 2}))
    fmt.Println(maps.Equal(map[string]int{"a": 1}, map[string]int{"a": 2}))
}
true
false

Q45. Can structs be compared with ==, and can they be map keys?

Yes, if all their fields are comparable. Two struct values are equal when every field is equal. Such structs can also be map keys, which is useful for keys made of two parts, like a grid point.

package main

import "fmt"

type Point struct {
    X, Y int
}

func main() {
    fmt.Println(Point{1, 2} == Point{1, 2})

    visited := map[Point]bool{}
    visited[Point{3, 4}] = true
    fmt.Println(visited[Point{3, 4}], visited[Point{0, 0}])
}
true
true false

If a struct has a slice, map or function field, == does not compile and the struct cannot be a map key.

Functions, Structs and Interface Go Interview Questions with Answers

These Go interview questions cover how you organise code. Interfaces and method sets come up in almost every technical round, so give them extra time.

Q46. Can a Go function return more than one value?

Yes. A Go function can return any number of values. The most common pattern is returning a result and an error, so the caller can check if something went wrong.

package main

import (
    "errors"
    "fmt"
)

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

func main() {
    result, err := divide(10, 4)
    fmt.Println(result, err)

    _, err = divide(1, 0)
    fmt.Println(err)
}
2.5 <nil>
cannot divide by zero

You can also name the return values, such as func split(n int) (half, rest int). Named results are useful for short functions and for changing the result inside a defer.

Q47. What are variadic functions?

A variadic function accepts any number of arguments of one type. You write ... before the type of the last parameter, and inside the function it becomes a slice. fmt.Println and append are variadic.

package main

import "fmt"

func sum(numbers ...int) int {
    total := 0
    for _, n := range numbers {
        total += n
    }
    return total
}

func main() {
    fmt.Println(sum())
    fmt.Println(sum(1, 2, 3))

    marks := []int{10, 20, 30}
    fmt.Println(sum(marks...)) // spread a slice with ...
}
0
6
60

Q48. What is a closure?

A closure is a function that uses variables from outside its own body. The function “remembers” those variables, even after the outer function has returned. So each closure can keep its own private state.

package main

import "fmt"

// counter returns a function that remembers count.
func counter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

func main() {
    next := counter()
    fmt.Println(next(), next(), next())

    other := counter() // a fresh, separate count
    fmt.Println(other())
}
1 2 3
1

Closures are used for callbacks, middleware, goroutines and small helpers like sort compare functions.

Q49. What does defer do, and in what order do deferred calls run?

defer schedules a function call to run when the surrounding function returns, whether it returns normally or panics. It is mostly used for clean-up, such as closing files, releasing locks and closing database rows.

Deferred calls run in last in, first out (LIFO) order, like a stack of plates. So the last defer you write runs first.

package main

import "fmt"

func main() {
    defer fmt.Println("first defer")
    defer fmt.Println("second defer")
    defer fmt.Println("third defer")
    fmt.Println("main body")
}
main body
third defer
second defer
first defer

Q50. When are a deferred call’s arguments evaluated?

The arguments are evaluated right away, when the defer line runs, not later when the call happens. So a deferred fmt.Println(x) prints the value x had at that moment. If you want the latest value, defer a closure instead.

package main

import "fmt"

func main() {
    x := 1
    defer fmt.Println("defer with argument:", x) // x is 1 here
    defer func() { fmt.Println("defer with closure:", x) }()
    x = 2
}
defer with closure: 2
defer with argument: 1

Q51. What is a struct?

A struct is a type that groups related fields together, like a form with named boxes. For example, an Employee has a name, an age and a salary. Structs are how you model data in Go.

package main

import "fmt"

type Employee struct {
    Name   string
    Age    int
    Salary float64
}

func main() {
    e := Employee{Name: "Asha", Age: 29, Salary: 75000}
    e.Age++ // fields are reached with a dot
    fmt.Println(e.Name, e.Age)
    fmt.Printf("%+v\n", e) // %+v prints field names too
}
Asha 30
{Name:Asha Age:30 Salary:75000}

Q52. What is struct embedding, and is it the same as inheritance?

Embedding means putting one type inside a struct without a field name. The outer struct then gets the inner type’s fields and methods “promoted”, so you can call them directly. However, it is composition, not inheritance. The outer type is not a subtype of the inner one, and you cannot pass it where the inner type is expected.

package main

import "fmt"

type Address struct {
    City string
}

func (a Address) Label() string { return "City: " + a.City }

type Customer struct {
    Name    string
    Address // embedded, no field name
}

func main() {
    c := Customer{Name: "Ravi", Address: Address{City: "Pune"}}
    fmt.Println(c.City)    // promoted field
    fmt.Println(c.Label()) // promoted method
}
Pune
City: Pune

So embedding is “has a” with a shortcut, while inheritance is “is a”.

Q53. What is a method, and what is a receiver?

A method is a function attached to a type. The receiver is the special parameter written before the method name, and it is the value the method works on. You can add methods to any type you define in your package, not just structs.

package main

import "fmt"

type Rectangle struct {
    Width, Height float64
}

// (r Rectangle) is the receiver.
func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

type Celsius float64

func (c Celsius) Fahrenheit() float64 { return float64(c)*9/5 + 32 }

func main() {
    fmt.Println(Rectangle{Width: 3, Height: 4}.Area())
    fmt.Println(Celsius(100).Fahrenheit())
}
12
212

Q54. When should you use a pointer receiver instead of a value receiver?

A value receiver gets a copy, so changes inside the method are lost. A pointer receiver gets the address, so it can change the original value and avoids copying big structs.

Use a pointer receiver when the method changes the value, when the struct is large, or when it holds something that must not be copied, such as a sync.Mutex. Also, keep all methods on a type consistent. If one needs a pointer, make them all pointers.

package main

import "fmt"

type Wallet struct {
    Balance int
}

func (w Wallet) AddCopy(amount int)     { w.Balance += amount } // changes a copy
func (w *Wallet) AddPointer(amount int) { w.Balance += amount } // changes the original

func main() {
    w := Wallet{Balance: 100}
    w.AddCopy(50)
    fmt.Println(w.Balance)
    w.AddPointer(50) // Go takes &w for you
    fmt.Println(w.Balance)
}
100
150

Q55. What is an interface?

An interface is a type that lists method signatures. Any type that has those methods can be used where the interface is expected. So an interface describes what something can do, not what it is.

For example, io.Writer has one method, Write([]byte) (int, error). A file, a network connection, a buffer and an HTTP response all satisfy it, so fmt.Fprintf can write to any of them. Small interfaces like this are the Go style.

Q56. How does a type implement an interface in Go?

Implicitly. If a type has all the methods an interface lists, it satisfies that interface automatically. There is no implements keyword. So packages stay loosely connected, and you can define an interface later for types you do not own.

package main

import "fmt"

type Shape interface {
    Area() float64
}

type Square struct{ Side float64 }
type Circle struct{ Radius float64 }

func (s Square) Area() float64 { return s.Side * s.Side }
func (c Circle) Area() float64 { return 3.14 * c.Radius * c.Radius }

func main() {
    shapes := []Shape{Square{Side: 2}, Circle{Radius: 1}}
    for _, s := range shapes {
        fmt.Printf("%T has area %.2f\n", s, s.Area())
    }
}
main.Square has area 4.00
main.Circle has area 3.14

Q57. What is the empty interface, and what is any?

The empty interface, interface{}, has no methods, so every type satisfies it. It can hold a value of any type. Since Go 1.18, any is a built-in alias for interface{}, so the two mean exactly the same thing.

It is useful for things like fmt.Println(args ...any) and decoding unknown JSON. However, you lose type safety, so prefer concrete types or generics when you can.

Q58. What is a type assertion, and what is a type switch?

A type assertion gets the concrete value out of an interface, like v.(string). Use the two-value form, s, ok := v.(string), because the one-value form panics if the type is wrong. A type switch checks several types in one go.

package main

import "fmt"

func describe(v any) string {
    switch x := v.(type) {
    case int:
        return fmt.Sprintf("int doubled is %d", x*2)
    case string:
        return "string of length " + fmt.Sprint(len(x))
    case nil:
        return "nil value"
    default:
        return fmt.Sprintf("other type %T", x)
    }
}

func main() {
    var v any = "hello"
    s, ok := v.(string)
    fmt.Println(s, ok)
    _, ok = v.(int) // safe: no panic
    fmt.Println(ok)

    fmt.Println(describe(21))
    fmt.Println(describe("go"))
    fmt.Println(describe(3.5))
}
hello true
false
int doubled is 42
string of length 2
other type float64

Q59. Why can an interface holding a nil pointer be non-nil?

An interface value has two parts: a type and a value. It is nil only when both parts are empty. If you store a nil *MyError in an error, the type part is set to *MyError, so the interface is not nil, even though the pointer inside is.

package main

import "fmt"

type MyError struct{}

func (e *MyError) Error() string { return "my error" }

func check(fail bool) error {
    var p *MyError // nil pointer
    if fail {
        p = &MyError{}
    }
    return p // wrong: always returns a non-nil interface
}

func main() {
    err := check(false)
    fmt.Println(err == nil)
}
false

So the fix is to return a plain nil when there is no error, not a typed nil pointer.

Q60. What are generics, and what is a type constraint?

Generics, added in Go 1.18, let you write one function or type that works with many types. You add type parameters in square brackets, such as [T any]. A type constraint says which types are allowed for T. A constraint is an interface, such as any, comparable or cmp.Ordered.

package main

import (
    "cmp"
    "fmt"
)

// Largest works for any ordered type: ints, floats, strings.
func Largest[T cmp.Ordered](items []T) T {
    best := items[0]
    for _, item := range items[1:] {
        if item > best {
            best = item
        }
    }
    return best
}

// Stack is a generic type.
type Stack[T any] struct{ items []T }

func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }

func main() {
    fmt.Println(Largest([]int{3, 9, 2}))
    fmt.Println(Largest([]string{"kiwi", "apple", "mango"}))

    var s Stack[string]
    s.Push("a")
    s.Push("b")
    fmt.Println(s.items)
}
9
mango
[a b]

Q61. When should you use generics, and when an interface?

Use generics when the code is the same for every type and only the type changes. Good examples are containers (stacks, sets, caches) and helpers like Map, Filter and Max. Use an interface when each type does the work in its own way, such as different Shape types each computing their own area.

A simple rule from the Go team is this. If you find yourself writing the exact same code several times with only the types different, think about generics. Otherwise, start with plain types and interfaces.

Q62. Are function arguments passed by value or by reference?

Go always passes arguments by value, which means the function gets a copy. However, some types hold a pointer inside. So copying a slice, map, channel, pointer or function value still lets the function reach the same underlying data.

package main

import "fmt"

func changeInt(n int)            { n = 100 }
func changePtr(n *int)           { *n = 100 }
func changeSlice(s []int)        { s[0] = 100 }
func changeMap(m map[string]int) { m["a"] = 100 }

func main() {
    x, y := 1, 1
    s := []int{1}
    m := map[string]int{"a": 1}

    changeInt(x)
    changePtr(&y)
    changeSlice(s)
    changeMap(m)
    fmt.Println(x, y, s, m)
}
1 100 [100] map[a:100]

So if a function must change a plain value like an int or a struct, pass a pointer.

Q63. What is a method set, and why does it matter for interfaces?

A method set is the list of methods that belong to a type. For a type T, the method set holds only methods with value receivers. For *T, it holds methods with both value and pointer receivers.

This matters for interfaces. If a method has a pointer receiver, only *T satisfies the interface, not T. That is why var s Saver = User{} fails to compile when Save has a pointer receiver, but var s Saver = &User{} works.

type Saver interface{ Save() }
type User struct{ Name string }

func (u *User) Save() {} // pointer receiver

var a Saver = &User{} // works: *User has Save
var b Saver = User{}  // compile error: User does not implement Saver

Q64. Can you embed an interface inside another interface or a struct?

Yes, both. Embedding interfaces inside an interface builds a bigger interface from smaller ones. For example, io.ReadWriter is io.Reader plus io.Writer.

Embedding an interface inside a struct gives the struct those methods, which are passed to whatever value you store in that field. This is handy for wrapping a type and overriding only one method, such as a logging wrapper around http.ResponseWriter. However, if the field is nil, calling a method panics.

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

type ReadWriter interface { // interface embedding
    Reader
    Writer
}

Q65. What do the comparable constraint and ~int mean in generics?

comparable is a built-in constraint for types that support == and !=. You need it for map keys or for checking equality inside generic code. The ~ sign means “any type whose underlying type is this”. So ~int allows int and also your own types like type UserID int.

package main

import "fmt"

type UserID int

type Integer interface {
    ~int | ~int64 // int, int64 and any type built on them
}

func Sum[T Integer](values []T) T {
    var total T
    for _, v := range values {
        total += v
    }
    return total
}

func Index[T comparable](items []T, target T) int {
    for i, item := range items {
        if item == target { // needs comparable
            return i
        }
    }
    return -1
}

func main() {
    fmt.Println(Sum([]UserID{10, 20, 30}))
    fmt.Println(Index([]string{"a", "b", "c"}, "c"))
}
60
2

Q66. What is range over a function (iterators), added in Go 1.23?

Since Go 1.23, a for range loop can loop over a function, called an iterator. The function receives a yield callback and calls it for each value. If yield returns false, the loop was stopped with break, so the iterator should stop too. The iter package names these types iter.Seq[V] and iter.Seq2[K, V].

package main

import (
    "fmt"
    "iter"
)

// Evens yields even numbers up to max.
func Evens(max int) iter.Seq[int] {
    return func(yield func(int) bool) {
        for n := 0; n <= max; n += 2 {
            if !yield(n) {
                return // the caller used break
            }
        }
    }
}

func main() {
    for n := range Evens(10) {
        if n > 6 {
            break
        }
        fmt.Print(n, " ")
    }
    fmt.Println()
}
0 2 4 6

Standard helpers such as slices.All, slices.Values and maps.Keys return iterators too.

Q67. What is reflection, and when should you avoid it?

Reflection, through the reflect package, lets a program look at types and values while it runs. For example, it can list a struct’s fields or read its tags. Packages like encoding/json and many ORMs use it.

However, reflection is slower, harder to read and moves type errors from compile time to run time. So avoid it in normal business code. Use interfaces, type switches or generics first, and keep reflection for general-purpose libraries.

Q68. How do struct tags work under the hood?

A struct tag is a string written after a field, such as json:"user_name". Go itself ignores tags. Packages read them at run time with reflection, through reflect.StructField.Tag.Get("json"), and use them to change their behaviour.

package main

import (
    "fmt"
    "reflect"
)

type User struct {
    Name  string `json:"user_name" db:"name"`
    Email string `json:"email,omitempty"`
}

func main() {
    t := reflect.TypeOf(User{})
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        fmt.Println(field.Name, "json:", field.Tag.Get("json"), "db:", field.Tag.Get("db"))
    }
}
Name json: user_name db: name
Email json: email,omitempty db:

So encoding/json reads the json tag, a database library reads the db tag, and a validator reads a validate tag.

Error Handling Go Interview Questions with Answers

Go handles errors as normal values. These Go interview questions test that idea, and interviewers often ask you to write a small custom error on the spot.

Q69. Why does Go use error values instead of exceptions?

In Go, a function that can fail returns an error as its last value, and the caller checks it with if err != nil. There are no try and catch blocks. The Go team chose this so errors are visible right where they happen, and you cannot ignore them without noticing.

This makes the control flow easy to follow, because there are no hidden jumps. The cost is more if err != nil lines, but each one is a clear decision about what to do with the failure.

package main

import (
    "fmt"
    "os"
)

func main() {
    _, err := os.ReadFile("missing.txt")
    if err != nil {
        fmt.Println("could not read file:", err)
        return
    }
    fmt.Println("file read")
}
could not read file: open missing.txt: no such file or directory

Q70. How do you create a custom error type?

error is just an interface with one method, Error() string. So any type with that method is an error. A custom error type lets you carry extra data, such as a field name or an HTTP status.

package main

import (
    "errors"
    "fmt"
)

type ValidationError struct {
    Field   string
    Problem string
}

func (e *ValidationError) Error() string {
    return e.Field + ": " + e.Problem
}

func validateAge(age int) error {
    if age < 18 {
        return &ValidationError{Field: "age", Problem: "must be 18 or more"}
    }
    return nil
}

func main() {
    err := validateAge(15)
    fmt.Println(err)

    var ve *ValidationError
    if errors.As(err, &ve) {
        fmt.Println("bad field:", ve.Field)
    }
}
age: must be 18 or more
bad field: age

For simple messages, errors.New("text") or fmt.Errorf("...") is enough.

Q71. How do you wrap an error with %w?

Wrapping adds context to an error while keeping the original inside it. You use fmt.Errorf with the %w verb. Callers can still find the original with errors.Is or errors.As, and errors.Unwrap returns the inner error.

package main

import (
    "errors"
    "fmt"
)

var ErrNotFound = errors.New("not found")

func findUser(id int) error {
    return fmt.Errorf("find user %d: %w", id, ErrNotFound)
}

func main() {
    err := findUser(42)
    fmt.Println(err)
    fmt.Println(errors.Is(err, ErrNotFound))
    fmt.Println(errors.Unwrap(err) == ErrNotFound)
}
find user 42: not found
true
true

If you use %v instead of %w, the text looks the same, but the chain is broken and errors.Is returns false.

Q72. What is the difference between errors.Is and errors.As?

errors.Is checks whether any error in the chain equals a specific value, usually a sentinel error like io.EOF or sql.ErrNoRows. errors.As checks whether any error in the chain has a specific type, and if so, it copies it into your variable so you can read its fields.

FunctionLooks forExample
errors.Is(err, target)A specific error valueerrors.Is(err, os.ErrNotExist)
errors.As(err, &target)A specific error typeerrors.As(err, &pathErr) to read pathErr.Path

So use Is for “which error is it?” and As for “give me the details”. Both walk through wrapped errors, so never compare wrapped errors with ==.

Q73. What does errors.Join do?

errors.Join, added in Go 1.20, combines several errors into one. It is useful when you check many things and want to report all the problems, not just the first. errors.Is and errors.As still find each inner error.

package main

import (
    "errors"
    "fmt"
)

var ErrNoName = errors.New("name is empty")
var ErrBadAge = errors.New("age is negative")

func validate(name string, age int) error {
    var errs []error
    if name == "" {
        errs = append(errs, ErrNoName)
    }
    if age < 0 {
        errs = append(errs, ErrBadAge)
    }
    return errors.Join(errs...) // nil if the slice is empty
}

func main() {
    err := validate("", -5)
    fmt.Println(err)
    fmt.Println(errors.Is(err, ErrBadAge))
    fmt.Println(validate("Asha", 30) == nil)
}
name is empty
age is negative
true
true

Q74. What are panic and recover?

panic stops normal execution of the current goroutine. Deferred functions still run, and if nothing recovers, the program crashes with a stack trace. recover stops a panic, but it only works when called inside a deferred function.

package main

import "fmt"

func safeDivide(a, b int) (result int, err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("recovered: %v", r)
        }
    }()
    return a / b, nil // panics when b is 0
}

func main() {
    fmt.Println(safeDivide(10, 2))
    fmt.Println(safeDivide(1, 0))
}
5 <nil>
0 recovered: runtime error: integer divide by zero

Also, a panic in one goroutine cannot be recovered by another goroutine. So each goroutine that might panic needs its own deferred recover.

Q75. When is it acceptable to panic?

Panic only for bugs and impossible states, not for normal errors. Normal problems, such as bad input, a missing file or a failed network call, should return an error.

Here are the usual acceptable cases.

  • A programming bug, such as an index out of range or a broken invariant.
  • Setup that cannot fail in a correct program, such as regexp.MustCompile with a fixed pattern.
  • Startup failures in main, where the app cannot run at all, although log.Fatal is more common there.

HTTP servers in Go recover panics in handlers so one bad request does not crash the whole server. However, you should still fix the bug that caused it.

Q76. What is a sentinel error?

A sentinel error is a fixed, exported error value that callers can check for. Examples are io.EOF, sql.ErrNoRows and os.ErrNotExist. You create one at package level with errors.New, and the name usually starts with Err.

var ErrInsufficientFunds = errors.New("insufficient funds")

func Withdraw(balance, amount int) error {
    if amount > balance {
        return fmt.Errorf("withdraw %d: %w", amount, ErrInsufficientFunds)
    }
    return nil
}

// Caller
if errors.Is(err, ErrInsufficientFunds) {
    // show a friendly message
}

Sentinel errors become part of your package API, so only export the ones callers really need to check.

Q77. Should you log an error and also return it?

Usually no. If every layer logs and returns, one failure shows up five times in the logs, which makes them noisy and hard to read. The common rule is: handle the error once. Either deal with it (log it and continue, retry or use a fallback), or add context and return it.

In a typical service, lower layers wrap and return errors. The top layer, such as the HTTP handler or main, logs the error once with the full context and decides what to send back to the user.

Q78. How do you add useful context to an error without losing the original?

Wrap it with fmt.Errorf and %w, and add what you were doing and with which data, such as an ID or a file name. Keep the message short and lowercase, and do not repeat words like “error” or “failed” at every level.

package main

import (
    "errors"
    "fmt"
    "os"
)

func loadConfig(path string) error {
    _, err := os.ReadFile(path)
    if err != nil {
        return fmt.Errorf("load config %q: %w", path, err)
    }
    return nil
}

func startApp() error {
    if err := loadConfig("app.yaml"); err != nil {
        return fmt.Errorf("start app: %w", err)
    }
    return nil
}

func main() {
    err := startApp()
    fmt.Println(err)
    fmt.Println("file missing:", errors.Is(err, os.ErrNotExist))
}
start app: load config "app.yaml": open app.yaml: no such file or directory
file missing: true

The message reads like a path from the top to the cause, and errors.Is still finds the original os.ErrNotExist.

Concurrency Go Interview Questions with Answers

Concurrency is the most asked topic in Go interviews. These Go interview questions cover goroutines, channels and the sync package, so practise each example until you can explain every line.

Q79. What is a goroutine?

A goroutine is a function that runs at the same time as other functions, managed by the Go runtime. You start one by writing go before a function call. Goroutines are very light. Each one starts with a small stack of a few kilobytes that grows when needed, so one program can run thousands or even millions of them.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    results := make([]string, 3)

    for i := 0; i < 3; i++ {
        wg.Add(1)
        go func() { // runs at the same time as main
            defer wg.Done()
            results[i] = fmt.Sprintf("task %d done", i)
        }()
    }
    wg.Wait() // wait for all three goroutines
    fmt.Println(results)
}
[task 0 done task 1 done task 2 done]

Each goroutine writes to its own slot in the slice, so there is no data race, and the output order is fixed.

Q80. How is a goroutine different from an operating system thread?

A thread is managed by the operating system, and a goroutine is managed by the Go runtime. The runtime runs many goroutines on a small number of OS threads, so goroutines are much cheaper to create and switch between.

FeatureGoroutineOS thread
Managed byGo runtime schedulerOperating system
Starting stackA few kilobytes, grows as neededUsually about 1 MB or more
Cost to createVery cheapMuch more expensive
SwitchingFast, in user spaceSlower, needs the kernel
Typical countThousands to millionsHundreds to a few thousand

So in Go, you start a goroutine for each task and let the runtime map them onto threads.

Go interview questions comparison of goroutines and operating system threads
Goroutines are cheap and managed by the Go runtime, while OS threads are heavier and managed by the operating system.

Q81. What is the Go scheduler, and what do G, M and P mean?

The Go scheduler decides which goroutine runs on which thread. It uses the GMP model.

  • G (goroutine): a piece of work, with its own stack.
  • M (machine): an OS thread that actually runs code.
  • P (processor): a slot that holds a local run queue of goroutines. An M needs a P to run Go code. The number of Ps equals GOMAXPROCS.

Each P has its own queue, so there is little locking. When a P runs out of work, it steals goroutines from another P, which keeps all CPUs busy. If a goroutine blocks on a system call, the M gives up its P, so another M can keep running other goroutines. Since Go 1.14, the scheduler can also pause long-running goroutines (preemption), so one busy loop cannot block others.

Q82. What is a channel?

A channel is a typed pipe that goroutines use to send values to each other safely. You create one with make(chan int), send with ch <- v and receive with v := <-ch. Channels also synchronise goroutines, because a send or receive can wait until the other side is ready.

package main

import "fmt"

func main() {
    messages := make(chan string)

    go func() {
        messages <- "order 101 packed" // send
    }()

    msg := <-messages // receive: waits until a value arrives
    fmt.Println(msg)
}
order 101 packed

You can also make send-only (chan<- int) and receive-only (<-chan int) channel types, which make function signatures clearer.

Q83. What is the difference between buffered and unbuffered channels?

An unbuffered channel, make(chan int), has no storage. Here, a send waits until a receiver takes the value, so both sides meet at the same moment, like handing over a parcel in person. A buffered channel, make(chan int, 3), holds up to 3 values. A send waits only when the buffer is full, and a receive waits only when it is empty, like a letterbox.

package main

import "fmt"

func main() {
    jobs := make(chan string, 2) // buffered: room for 2
    jobs <- "email"              // does not wait
    jobs <- "sms"                // does not wait
    fmt.Println(len(jobs), cap(jobs))

    fmt.Println(<-jobs, <-jobs) // first in, first out
}
2 2
email sms

So use unbuffered channels when you want a guaranteed hand-off. Use buffered channels to smooth out short bursts or to limit work, as in a semaphore.

Q84. What happens when you send to or receive from a closed channel?

Sending to a closed channel causes a panic. Receiving from a closed channel never blocks. It returns any values still in the buffer, and after that it returns the zero value at once. The two-value receive tells you which case you have.

package main

import "fmt"

func main() {
    ch := make(chan int, 2)
    ch <- 10
    close(ch)

    v, ok := <-ch
    fmt.Println(v, ok) // buffered value still there
    v, ok = <-ch
    fmt.Println(v, ok) // closed and empty: zero value, false
}
10 true
0 false

Also, closing a channel twice panics, and so does closing a nil channel.

Q85. Who should close a channel, and when?

The sender closes the channel, never the receiver, and only when no more values will be sent. Closing is a signal to receivers that the stream is finished, so a for range loop over the channel can end.

If many goroutines send on one channel, none of them should close it on its own. Instead, use a sync.WaitGroup and close the channel after all senders finish. Also, you do not have to close every channel. A channel that nobody ranges over is cleaned up by the garbage collector.

package main

import (
    "fmt"
    "sync"
)

func main() {
    results := make(chan int)
    var wg sync.WaitGroup

    for i := 1; i <= 3; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            results <- i * 10
        }()
    }

    go func() {
        wg.Wait()
        close(results) // closed once, after every sender is done
    }()

    total := 0
    for r := range results { // ends when results is closed
        total += r
    }
    fmt.Println("total:", total)
}
total: 60

Q86. What does select do?

select waits on several channel operations at once and runs the first one that is ready. If several are ready, it picks one at random. A default case makes it non-blocking, so it runs at once when no channel is ready.

package main

import "fmt"

func main() {
    orders := make(chan string, 1)
    alerts := make(chan string, 1)
    alerts <- "low stock"

    select {
    case o := <-orders:
        fmt.Println("order:", o)
    case a := <-alerts:
        fmt.Println("alert:", a)
    }

    select {
    case o := <-orders:
        fmt.Println("order:", o)
    default:
        fmt.Println("nothing ready, moving on")
    }
}
alert: low stock
nothing ready, moving on

Q87. How do you add a timeout to a channel operation?

Use select with a timer channel. time.After(d) sends a value after the given time, so if the result has not arrived by then, the timeout case runs. In real services, you usually use ctx.Done() from a context with a deadline.

package main

import (
    "fmt"
    "time"
)

func main() {
    result := make(chan string)

    go func() {
        time.Sleep(200 * time.Millisecond) // slow work
        result <- "report ready"
    }()

    select {
    case r := <-result:
        fmt.Println(r)
    case <-time.After(50 * time.Millisecond):
        fmt.Println("timed out")
    }
}
timed out

In this example, the slow goroutine is left blocked forever, because nobody receives its value. Making result a buffered channel with size 1 lets it finish and exit, which avoids a leak.

Q88. What is a WaitGroup, and what does wg.Go add in newer Go versions?

A sync.WaitGroup waits for a group of goroutines to finish. You call Add(n) before starting them, each goroutine calls Done() when finished, and Wait() blocks until the count reaches zero.

Go 1.25 added wg.Go(func()). It calls Add(1), starts the goroutine and calls Done() for you, so you cannot forget either step.

var wg sync.WaitGroup
for _, url := range urls {
    wg.Go(func() { // Go 1.25+: Add and Done are handled for you
        check(url)
    })
}
wg.Wait()

A common bug is calling wg.Add(1) inside the goroutine. Then Wait might run before Add, and return too early.

Q89. What is a Mutex, and what is an RWMutex?

A sync.Mutex is a lock that lets only one goroutine at a time into a piece of code. You call Lock() before touching shared data and release it after, usually with a deferred call. A sync.RWMutex allows many readers at the same time, but only one writer, and no readers while writing.

package main

import (
    "fmt"
    "sync"
)

type Counter struct {
    mu    sync.Mutex
    count int
}

func (c *Counter) Increment() {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.count++
}

func main() {
    var c Counter
    var wg sync.WaitGroup
    for i := 0; i < 1000; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            c.Increment()
        }()
    }
    wg.Wait()
    fmt.Println("count:", c.count)
}
count: 1000

Without the mutex, the result would often be less than 1000, because increments would overwrite each other. Use RWMutex only when reads are much more common than writes, such as a config cache.

Q90. What does sync.Once do?

sync.Once makes sure a function runs only one time, even if many goroutines call it at once. It is used for lazy setup, such as opening a shared connection or loading config on first use. Go 1.21 also added sync.OnceFunc and sync.OnceValue helpers.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var once sync.Once
    var wg sync.WaitGroup
    setup := func() { fmt.Println("loading config") }

    for i := 0; i < 5; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            once.Do(setup) // only the first call runs setup
        }()
    }
    wg.Wait()

    getPort := sync.OnceValue(func() int { return 8080 })
    fmt.Println(getPort(), getPort())
}
loading config
8080 8080

Q91. What are atomic operations?

Atomic operations, from sync/atomic, read or change a single value in one step that cannot be interrupted. So they are safe across goroutines without a mutex, and they are faster for simple things like counters and flags. Since Go 1.19, typed values such as atomic.Int64 and atomic.Bool make them easy to use.

package main

import (
    "fmt"
    "sync"
    "sync/atomic"
)

func main() {
    var requests atomic.Int64
    var wg sync.WaitGroup

    for i := 0; i < 500; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            requests.Add(1)
        }()
    }
    wg.Wait()
    fmt.Println("requests:", requests.Load())
}
requests: 500

Use atomics for one value. When you must update several fields together, use a mutex.

Q92. What is a data race, and how do you find one?

A data race happens when two goroutines access the same memory at the same time, at least one of them writes, and there is no synchronisation. The results are unpredictable, and bugs may appear only sometimes, which makes them hard to find.

Go has a built-in race detector. Run go test -race ./... or go run -race main.go, and it prints the exact lines where the conflicting reads and writes happened. Run your tests with -race in CI. To fix a race, use a mutex, an atomic value or a channel, so only one goroutine owns the data at a time.

Q93. What is a deadlock, and when does Go detect it?

A deadlock happens when goroutines wait for each other forever, so none can move on. A simple example is sending on an unbuffered channel when nobody will ever receive.

func main() {
    ch := make(chan int)
    ch <- 1 // nobody receives, so main waits forever
}

// fatal error: all goroutines are asleep - deadlock!

Go detects a deadlock only when every goroutine in the program is blocked. If even one goroutine is still running, such as an HTTP server, the runtime cannot tell, and the stuck goroutines just hang. So use timeouts, contexts and a consistent lock order to avoid deadlocks.

Q94. What is a goroutine leak, and how do you prevent it?

A goroutine leak happens when a goroutine never finishes, usually because it waits forever on a channel or a lock. Leaked goroutines keep their memory, so in a long-running server the count grows until the service slows down or crashes.

Here are ways to prevent leaks.

  • Give every goroutine a clear way to stop, such as a cancelled context or a closed channel.
  • Use buffered channels when a sender might be left with no receiver, such as after a timeout.
  • Always set timeouts on network calls.
  • Watch the goroutine count with runtime.NumGoroutine() or the pprof goroutine profile, and test with go.uber.org/goleak.

Q95. What is the context package used for?

The context package carries three things across function calls and goroutines: a deadline or timeout, a cancel signal and request-scoped values such as a request ID. When the context is cancelled, every function that watches ctx.Done() can stop its work early.

package main

import (
    "context"
    "fmt"
    "time"
)

func slowQuery(ctx context.Context) error {
    select {
    case <-time.After(500 * time.Millisecond): // the real work
        return nil
    case <-ctx.Done(): // cancelled or timed out
        return ctx.Err()
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
    defer cancel() // always call cancel to free resources

    err := slowQuery(ctx)
    fmt.Println(err)
}
context deadline exceeded

Pass ctx as the first parameter of functions that do I/O, and never store it inside a struct. Our Go context interview questions cover it in detail.

Q96. How do you build a worker pool in Go?

A worker pool starts a fixed number of goroutines that read jobs from one channel and send results to another. So you control how much work runs at once, instead of starting a goroutine for every job.

package main

import (
    "fmt"
    "sync"
)

func main() {
    jobs := make(chan int, 10)
    results := make(chan int, 10)
    var wg sync.WaitGroup

    for w := 1; w <= 3; w++ { // 3 workers
        wg.Add(1)
        go func() {
            defer wg.Done()
            for n := range jobs {
                results <- n * n // the "work": square the number
            }
        }()
    }

    for n := 1; n <= 5; n++ {
        jobs <- n
    }
    close(jobs) // workers exit when jobs run out

    wg.Wait()
    close(results)

    sum := 0
    for r := range results {
        sum += r
    }
    fmt.Println("sum of squares:", sum)
}
sum of squares: 55

Q97. What are fan-out and fan-in patterns?

Fan-out means starting several goroutines that read from the same channel, so the work is spread across them. Fan-in means merging results from several channels into one channel. A worker pool uses fan-out, and collecting all worker outputs into one channel is fan-in.

package main

import (
    "fmt"
    "sort"
    "sync"
)

// merge combines many channels into one (fan-in).
func merge(inputs ...<-chan string) <-chan string {
    out := make(chan string)
    var wg sync.WaitGroup
    for _, in := range inputs {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for v := range in {
                out <- v
            }
        }()
    }
    go func() { wg.Wait(); close(out) }()
    return out
}

func producer(name string, count int) <-chan string {
    ch := make(chan string)
    go func() {
        defer close(ch)
        for i := 1; i <= count; i++ {
            ch <- fmt.Sprintf("%s-%d", name, i)
        }
    }()
    return ch
}

func main() {
    var all []string
    for v := range merge(producer("A", 2), producer("B", 2)) {
        all = append(all, v)
    }
    sort.Strings(all) // arrival order varies, so sort
    fmt.Println(all)
}
[A-1 A-2 B-1 B-2]

Q98. What does “do not communicate by sharing memory” mean?

The full Go saying is: “Do not communicate by sharing memory; instead, share memory by communicating.” It means you should pass data between goroutines through channels, so only one goroutine owns the data at a time, instead of many goroutines reading and writing the same variable with locks.

However, it is a guideline, not a strict rule. A mutex is often simpler for protecting a shared counter or cache. So use channels to pass ownership of data or signal events, and use a mutex to guard shared state.

Q99. What is errgroup, and how is it different from a WaitGroup?

errgroup comes from golang.org/x/sync/errgroup. Like a WaitGroup, it waits for a group of goroutines. However, each goroutine returns an error, and Wait() returns the first error. With errgroup.WithContext, the first failure also cancels the shared context, so the other goroutines can stop early. SetLimit(n) caps how many run at once.

g, ctx := errgroup.WithContext(ctx)
g.SetLimit(5) // at most 5 at a time

for _, id := range orderIDs {
    g.Go(func() error {
        return syncOrder(ctx, id) // return an error to stop the group
    })
}
if err := g.Wait(); err != nil {
    return fmt.Errorf("sync orders: %w", err)
}

So use a WaitGroup when goroutines cannot fail, and errgroup when they can.

Q100. How do you limit how many goroutines run at the same time?

There are three common ways. A worker pool starts a fixed number of goroutines. A buffered channel can work as a semaphore, where each goroutine sends before it starts and receives when it ends. And errgroup has SetLimit.

package main

import (
    "fmt"
    "sync"
    "sync/atomic"
)

func main() {
    limit := make(chan struct{}, 2) // at most 2 at once
    var running, maxSeen atomic.Int32
    var wg sync.WaitGroup

    for i := 0; i < 6; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            limit <- struct{}{}        // take a slot (waits if full)
            defer func() { <-limit }() // give the slot back

            now := running.Add(1)
            for {
                old := maxSeen.Load()
                if now <= old || maxSeen.CompareAndSwap(old, now) {
                    break
                }
            }
            running.Add(-1)
        }()
    }
    wg.Wait()
    fmt.Println("never more than 2 at once:", maxSeen.Load() <= 2)
}
never more than 2 at once: true

Q101. What is sync.Cond, and when would you use it?

sync.Cond lets goroutines wait until some condition becomes true, and lets another goroutine wake them up. Wait() releases the lock and sleeps, Signal() wakes one waiter, and Broadcast() wakes all of them. Waiters must check the condition in a loop, because they may wake up before it is true.

It is rarely needed in everyday code, because channels usually do the job more simply. It is useful when many goroutines wait for the same state change, such as a queue that is no longer empty or a cache that has finished loading.

Q102. How do you build a rate limiter in Go?

The easiest way is the token bucket in golang.org/x/time/rate. You create a limiter with a rate and a burst size, then call Wait(ctx) to block until a token is free, or Allow() to check without waiting.

limiter := rate.NewLimiter(rate.Limit(10), 20) // 10 per second, bursts up to 20

func handler(w http.ResponseWriter, r *http.Request) {
    if !limiter.Allow() {
        http.Error(w, "too many requests", http.StatusTooManyRequests)
        return
    }
    // handle the request
}

For a simple fixed pace, you can also use a time.Ticker and wait on its channel before each call. For limits shared by many servers, keep the counters in Redis.

Q103. What happens to running goroutines when main returns?

When main returns, the whole program exits at once. All other goroutines are stopped immediately, even in the middle of their work, and their deferred calls do not run. So a goroutine that writes a file or sends a message may never finish.

package main

import (
    "fmt"
    "time"
)

func main() {
    go func() {
        time.Sleep(100 * time.Millisecond)
        fmt.Println("this never prints")
    }()
    fmt.Println("main is done")
}
main is done

That is why you wait for goroutines with a WaitGroup, a channel or errgroup before main returns.

Q104. How do you test concurrent code, for example with testing/synctest?

First, always run tests with -race, so the race detector checks every test. Then avoid time.Sleep in tests, because it makes them slow and flaky. Instead, wait on channels or WaitGroups, and pass timeouts through context.

Go 1.25 added the testing/synctest package. Inside synctest.Test, code runs in a “bubble” with a fake clock. Time moves forward instantly when all goroutines in the bubble are blocked, so a test of a 5-second timeout finishes in microseconds and gives the same result every time.

func TestTimeout(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
        defer cancel()

        time.Sleep(5 * time.Second) // fake clock: instant
        synctest.Wait()             // wait until goroutines settle
        if ctx.Err() != context.DeadlineExceeded {
            t.Fatal("expected timeout")
        }
    })
}

Q105. Why must you never copy a sync.Mutex after first use?

A sync.Mutex holds its lock state inside the struct. If you copy it, the copy gets a snapshot of that state, so two goroutines might lock two different mutexes and both enter the protected code. The same rule applies to WaitGroup, Once, Cond and atomic types.

This often happens by accident with value receivers or by passing a struct by value. So use pointer receivers on types that hold a mutex, and run go vet, whose copylocks check reports these copies.

type Cache struct {
    mu   sync.Mutex
    data map[string]string
}

func (c Cache) Get(k string) string { // wrong: copies the mutex
    c.mu.Lock()
    defer c.mu.Unlock()
    return c.data[k]
}

func (c *Cache) Set(k, v string) { // right: pointer receiver
    c.mu.Lock()
    defer c.mu.Unlock()
    c.data[k] = v
}

Standard Library, Testing and Tooling Go Interview Questions with Answers

Backend roles expect you to build, test and ship real services. So these Go interview questions cover net/http, JSON, testing and the go command.

Q106. How do you write a simple HTTP server with net/http?

You register handler functions on a ServeMux and start the server with http.ListenAndServe. Since Go 1.22, patterns can include the HTTP method and path variables, such as "GET /users/{id}", so simple APIs do not need a third-party router.

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    mux := http.NewServeMux()

    mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, Go!")
    })

    mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
        id := r.PathValue("id") // read the path variable
        fmt.Fprintf(w, "user %s\n", id)
    })

    log.Println("listening on :8080")
    log.Fatal(http.ListenAndServe(":8080", mux))
}

Each request runs in its own goroutine, so the server handles many clients at the same time. In production, use an http.Server with timeouts, as shown in the next answer.

Q107. How do you set timeouts on an HTTP server and client?

The default server and client have no timeouts, so a slow client or a slow API can hold a goroutine forever. Always set them.

// Server timeouts
srv := &http.Server{
    Addr:              ":8080",
    Handler:           mux,
    ReadHeaderTimeout: 5 * time.Second,  // time to read request headers
    ReadTimeout:       10 * time.Second, // time to read the whole request
    WriteTimeout:      15 * time.Second, // time to write the response
    IdleTimeout:       60 * time.Second, // keep-alive connections
}

// Client timeout for the whole request
client := &http.Client{Timeout: 5 * time.Second}

// Per-request deadline with context
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
resp, err := client.Do(req)

So the client timeout covers the whole call, and the context deadline lets the caller cancel early.

Q108. How do JSON struct tags work?

encoding/json reads the json tag on each exported field to decide the key name and options. Without a tag, it uses the field name as it is. Unexported (lowercase) fields are always skipped.

TagMeaning
json:"user_name"Use user_name as the key
json:"email,omitempty"Skip the field if it has the zero value
json:"-"Never encode or decode this field
json:"id,string"Encode a number as a JSON string
package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    Name     string `json:"name"`
    Email    string `json:"email,omitempty"`
    Password string `json:"-"`
    Age      int    `json:"age"`
}

func main() {
    data, _ := json.Marshal(User{Name: "Asha", Password: "secret", Age: 29})
    fmt.Println(string(data))

    var u User
    err := json.Unmarshal([]byte(`{"name":"Ravi","email":"ravi@example.com","age":31}`), &u)
    fmt.Println(u.Name, u.Email, u.Age, err)
}
{"name":"Asha","age":29}
Ravi ravi@example.com 31 <nil>

Q109. How do you read a file line by line?

Open the file with os.Open and wrap it in a bufio.Scanner. The scanner reads one line at a time, so even a huge file uses little memory. Always check scanner.Err() at the end.

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {
    // Create a small file for the example.
    os.WriteFile("orders.txt", []byte("pen,10\nbook,250\nbag,900\n"), 0644)
    defer os.Remove("orders.txt")

    file, err := os.Open("orders.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    lineNo := 0
    for scanner.Scan() {
        lineNo++
        parts := strings.Split(scanner.Text(), ",")
        fmt.Printf("line %d: item=%s price=%s\n", lineNo, parts[0], parts[1])
    }
    if err := scanner.Err(); err != nil {
        fmt.Println("read error:", err)
    }
}
line 1: item=pen price=10
line 2: item=book price=250
line 3: item=bag price=900

By default, a line can be up to 64 KB. For longer lines, call scanner.Buffer with a bigger size.

Q110. How do you write a unit test with go test?

Put tests in a file ending with _test.go, in the same package. Each test is a function named TestXxx that takes *testing.T. Run them with go test ./....

// file: mathx/add.go
package mathx

func Add(a, b int) int { return a + b }

// file: mathx/add_test.go
package mathx

import "testing"

func TestAdd(t *testing.T) {
    got := Add(2, 3)
    want := 5
    if got != want {
        t.Errorf("Add(2, 3) = %d, want %d", got, want)
    }
}

t.Errorf reports a failure and keeps going, while t.Fatalf stops that test at once. Use go test -v to see each test name and go test -cover to see coverage.

Q111. What are table-driven tests?

Table-driven tests put many test cases in a slice of structs, then loop over them. So adding a new case is one line, and every case runs the same checks. Calling t.Run gives each case its own name in the output.

func TestGrade(t *testing.T) {
    tests := []struct {
        name  string
        marks int
        want  string
    }{
        {"top score", 95, "A"},
        {"good score", 80, "B"},
        {"low score", 40, "C"},
    }

    for _, tc := range tests {
        t.Run(tc.name, func(t *testing.T) {
            if got := grade(tc.marks); got != tc.want {
                t.Errorf("grade(%d) = %q, want %q", tc.marks, got, tc.want)
            }
        })
    }
}

This is the standard testing style in Go, and the Go standard library uses it everywhere.

Q112. How do you write a benchmark?

A benchmark is a function named BenchmarkXxx that takes *testing.B. Since Go 1.24, the simplest form is a for b.Loop() loop, which handles the timing for you. Run benchmarks with go test -bench=. -benchmem to see time and memory per operation.

func BenchmarkJoin(b *testing.B) {
    parts := []string{"a", "b", "c", "d"}
    for b.Loop() { // Go 1.24+; older code uses for i := 0; i < b.N; i++
        _ = strings.Join(parts, ",")
    }
}

The output shows ns/op (time per operation), B/op (bytes allocated) and allocs/op. Compare two versions with the benchstat tool, because one run can be noisy.

Q113. What is fuzz testing in Go?

Fuzz testing, built in since Go 1.18, feeds random and changed inputs into your function to find crashes and edge cases you did not think of. A fuzz test is named FuzzXxx and takes *testing.F. You add a few seed inputs, and the fuzzer creates new ones from them.

func FuzzReverse(f *testing.F) {
    f.Add("hello") // seed input
    f.Fuzz(func(t *testing.T, s string) {
        twice := Reverse(Reverse(s))
        if twice != s {
            t.Errorf("Reverse twice changed %q to %q", s, twice)
        }
    })
}

Run it with go test -fuzz=FuzzReverse. When the fuzzer finds a failing input, it saves it under testdata/fuzz, so it becomes a normal test case from then on.

Q114. What do go vet and gofmt do?

gofmt formats your code in the one standard Go style: tabs, spacing and alignment. So every Go project looks the same, and code reviews skip style arguments. goimports does the same and also fixes import lines.

go vet looks for likely bugs that still compile. Examples are wrong Printf verbs, copied mutexes, unreachable code and struct tags with typos. Run both in your editor and in CI. Many teams also add staticcheck or golangci-lint for more checks.

Q115. How do you run tests with the race detector?

Add the -race flag: go test -race ./.... The race detector watches memory access while the tests run and reports any data race with the stack traces of both goroutines. You can also use go run -race and go build -race.

It makes programs slower and use more memory, so it is for tests and staging, not normal production builds. It only finds races in code that actually runs, so good test coverage matters.

Q116. How do you manage dependencies and versions with Go modules?

Go modules use semantic versions, such as v1.4.2. You add or upgrade a dependency with go get example.com/lib@v1.4.2, or @latest. The version goes into go.mod, and checksums go into go.sum.

Here are the key rules.

  • Go uses Minimal Version Selection: it picks the lowest version that meets every requirement, so builds are repeatable.
  • A new major version, v2 or above, has a different import path, such as example.com/lib/v2.
  • go list -m -u all shows available upgrades, and govulncheck ./... checks for known security issues.

Q117. What is the internal directory used for?

Packages inside a folder named internal can only be imported by code in the parent of that folder. For example, myapp/internal/db can be used by myapp/cmd/api, but another module cannot import it. The Go tool enforces this.

So internal lets you keep helper code private and change it freely, without worrying about breaking other projects. Most Go services put almost all their code under internal.

Q118. What does go generate do?

go generate runs commands written in special comments in your Go files, such as //go:generate stringer -type=Status. It is used to create code automatically, for example mocks, String() methods for enums or code from .proto files.

It does not run during go build. You run it yourself, and you usually commit the generated files to Git, so others can build without the tools.

Q119. How do you cross-compile for another operating system?

Set the GOOS and GOARCH environment variables before go build. Go includes everything it needs, so you do not have to install another compiler for pure Go code.

GOOS=linux GOARCH=amd64 go build -o app-linux ./cmd/api
GOOS=windows GOARCH=amd64 go build -o app.exe ./cmd/api
GOOS=darwin GOARCH=arm64 go build -o app-mac ./cmd/api

Run go tool dist list to see every supported pair. If your code uses cgo, cross-compiling is harder, because you also need a C compiler for the target.

Q120. What does the log/slog package give you?

log/slog, added in Go 1.21, gives you structured logging in the standard library. Each log line has a level (Debug, Info, Warn, Error), a message and key-value fields. A text handler prints key=value pairs, and a JSON handler prints JSON that log tools can search.

package main

import (
    "log/slog"
    "os"
)

func main() {
    // Drop the time field so this example prints the same output each run.
    opts := &slog.HandlerOptions{
        ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
            if a.Key == slog.TimeKey {
                return slog.Attr{}
            }
            return a
        },
    }
    logger := slog.New(slog.NewTextHandler(os.Stdout, opts))
    logger.Info("user logged in", "user_id", 42, "method", "otp")
    logger.Warn("slow query", "ms", 850)
}
level=INFO msg="user logged in" user_id=42 method=otp
level=WARN msg="slow query" ms=850

You can add common fields to every line with logger.With("service", "orders").

Q121. What is the embed package used for?

The embed package puts files into your compiled binary at build time. You add a //go:embed comment above a variable. So a web app can ship its HTML templates, CSS, SQL migrations or config defaults inside one binary, with nothing extra to copy.

import "embed"

//go:embed templates/*.html
var templates embed.FS

//go:embed version.txt
var version string

func main() {
    page, _ := templates.ReadFile("templates/home.html")
    fmt.Println(version, len(page))
}

Q122. What are build tags (build constraints)?

A build tag is a comment at the top of a file that decides when the file is included in a build. It uses the //go:build line with simple logic, such as //go:build linux && amd64 or //go:build integration.

They are used for code that only works on one operating system, for slow integration tests that run only with go test -tags=integration, and for debug-only code. Also, file names like file_windows.go act as a build constraint automatically.

Q123. What is a Go workspace, and what is go.work?

A workspace lets you work on several modules together on your machine. You create a go.work file with go work init ./api ./shared. Then changes in shared are used by api straight away, without publishing a new version.

It is meant for local development, so most teams do not commit go.work. Before workspaces, people used replace lines in go.mod, which were easy to forget and commit by mistake.

Q124. What does go mod tidy do, and what is vendoring?

go mod tidy cleans up go.mod and go.sum. It adds any module your code imports but is missing, and removes modules you no longer use. Run it before every commit that changes imports.

Vendoring, with go mod vendor, copies all dependency source code into a vendor folder inside your project. Then builds do not need to download anything. Some companies use it for offline builds or strict reviews of third-party code, but most projects rely on the module proxy instead.

Q125. What is cgo, and what does CGO_ENABLED=0 do?

cgo lets Go code call C code, using import "C". It is useful for using existing C libraries, such as SQLite. However, it makes builds slower, cross-compiling harder and the binary depends on C libraries on the target machine.

Setting CGO_ENABLED=0 turns cgo off, so you get a fully static pure Go binary. That binary can run in a tiny image like scratch or distroless. So most Go services are built with CGO_ENABLED=0 for Docker.

Q126. How do you write HTTP middleware in Go?

Middleware is a function that takes an http.Handler and returns a new http.Handler that does something before or after calling the original. It is used for logging, authentication, request IDs, panic recovery and timing.

package main

import (
    "fmt"
    "net/http"
    "net/http/httptest"
)

// logging wraps any handler and prints the method and path.
func logging(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("before:", r.Method, r.URL.Path)
        next.ServeHTTP(w, r) // call the real handler
        fmt.Println("after:", r.URL.Path)
    })
}

func hello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "hello")
}

func main() {
    handler := logging(http.HandlerFunc(hello))

    // httptest lets us call the handler without a real network.
    rec := httptest.NewRecorder()
    req := httptest.NewRequest("GET", "/greet", nil)
    handler.ServeHTTP(rec, req)
    fmt.Println("response:", rec.Body.String())
}
before: GET /greet
after: /greet
response: hello

You chain middleware by wrapping, such as logging(auth(mux)).

Q127. How does connection pooling work in database/sql?

*sql.DB is not one connection. It is a pool that opens connections when needed and reuses idle ones. It is safe for many goroutines, so you create it once at startup and share it.

You tune it with four settings.

db, err := sql.Open("pgx", dsn) // does not connect yet
if err != nil {
    log.Fatal(err)
}
if err := db.PingContext(ctx); err != nil { // check the connection
    log.Fatal(err)
}
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(25)
db.SetConnMaxLifetime(30 * time.Minute)
db.SetConnMaxIdleTime(5 * time.Minute)

Always close rows with defer rows.Close(), because open rows keep a connection busy. Forgetting this is a common cause of “too many connections” errors.

Q128. How do you prevent SQL injection in a Go service?

Never build SQL by joining strings with user input. Always use placeholders, so the database treats the input as data, not as SQL code. PostgreSQL drivers use $1, $2, and MySQL uses ?.

// Wrong: user input becomes part of the SQL text
query := "SELECT id FROM users WHERE email = '" + email + "'"

// Right: the value is sent separately from the SQL
row := db.QueryRowContext(ctx, "SELECT id FROM users WHERE email = $1", email)

For dynamic parts that cannot be placeholders, such as a sort column, check the value against a fixed allow-list. Also, give the database user only the permissions the service needs.

Performance and Advanced Go Interview Questions with Answers

Senior rounds check how well you understand memory, speed and project design. These are the last group of Go interview questions before the scenarios, and the answers here are what interviewers expect from experienced developers.

Q129. How does the Go garbage collector work, at a high level?

Go uses a concurrent, tri-colour mark and sweep garbage collector. “Mark” finds every object that is still reachable from your variables, and “sweep” frees the rest. “Concurrent” means most of this work runs at the same time as your program, so pauses are very short, usually well under a millisecond.

The tri-colour idea works like this. White objects are not yet checked, grey objects are found but their children are not checked yet, and black objects are fully checked. When no grey objects are left, everything still white is garbage. A write barrier keeps this correct while your goroutines keep changing pointers.

Go’s collector does not move objects and is not generational. So the best way to reduce GC work is simple: allocate less. Our Go memory and performance questions go further.

Q130. What is escape analysis?

Escape analysis is a check the compiler does to decide where each value lives. If a value is only used inside a function, it stays on the stack, which is fast and needs no garbage collection. If the value “escapes”, for example because you return a pointer to it or store it in a long-lived place, it moves to the heap.

func onStack() int {
    x := 42 // stays on the stack
    return x
}

func onHeap() *int {
    x := 42 // escapes: we return its address
    return &x
}

You can see the compiler’s decisions with go build -gcflags=-m. It prints lines like moved to heap: x. This helps you find unexpected heap allocations in hot code.

Q131. What is the difference between the stack and the heap in Go?

Each goroutine has its own stack, which holds local variables and function call frames. Stack memory is very cheap, because it is freed automatically when a function returns. The heap is shared memory for values that must live longer, and the garbage collector cleans it.

FeatureStackHeap
Owned byOne goroutineThe whole program
SpeedVery fastSlower to allocate
Freed byFunction returnGarbage collector
SizeStarts small, grows as neededLimited by memory
Decided byEscape analysisEscape analysis

In Go, you do not choose stack or heap yourself. The compiler decides, and your code works the same either way.

Q132. How do you profile a Go program with pprof?

pprof is Go’s built-in profiler. It shows where your program spends CPU time, which code allocates memory, and what every goroutine is doing. For a web service, import net/http/pprof and the profiles appear under /debug/pprof/.

import _ "net/http/pprof" // registers /debug/pprof handlers

func main() {
    // Serve pprof on a private port only, never on the public one.
    go http.ListenAndServe("localhost:6060", nil)
    // ... start your real server
}

Then you collect and read a profile with the go tool pprof command.

go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30   # CPU
go tool pprof http://localhost:6060/debug/pprof/heap                 # memory
go tool pprof -http=:8081 cpu.prof                                   # web view with flame graph

In tests, you can use go test -cpuprofile cpu.prof -memprofile mem.prof -bench=. to profile a benchmark.

Q133. What does sync.Pool do, and when should you use it?

sync.Pool keeps a set of temporary objects that can be reused, so you allocate less and the garbage collector has less work. You Get an object, use it, reset it and Put it back. The pool may drop objects at any GC, so it is only for things that are cheap to rebuild.

package main

import (
    "bytes"
    "fmt"
    "sync"
)

var bufferPool = sync.Pool{
    New: func() any { return new(bytes.Buffer) }, // called when the pool is empty
}

func render(name string) string {
    buf := bufferPool.Get().(*bytes.Buffer)
    defer func() {
        buf.Reset() // clean it before giving it back
        bufferPool.Put(buf)
    }()
    buf.WriteString("Hello, ")
    buf.WriteString(name)
    return buf.String()
}

func main() {
    fmt.Println(render("Asha"))
    fmt.Println(render("Ravi"))
}
Hello, Asha
Hello, Ravi

Use it for busy paths that allocate the same kind of buffer again and again, such as JSON encoding in an HTTP handler. Measure first, because a pool adds complexity.

Q134. What does GOMAXPROCS control?

GOMAXPROCS sets how many OS threads can run Go code at the same time, which is the number of Ps in the scheduler. By default, it equals the number of CPU cores. Goroutines blocked in system calls do not count against it.

Since Go 1.25, the runtime on Linux also respects the container’s CPU limit. So a pod limited to 2 CPUs gets GOMAXPROCS=2, even on a 64-core node, which avoids heavy CPU throttling. You can still set it yourself with the environment variable or runtime.GOMAXPROCS(n).

Q135. How do you reduce memory allocations in a hot path?

First, measure with a benchmark using -benchmem and a memory profile, so you fix the real problem. Then use these common techniques.

  • Pre-size slices and maps with make([]T, 0, n) and make(map[K]V, n).
  • Use strings.Builder or bytes.Buffer instead of + in loops.
  • Reuse buffers with sync.Pool.
  • Avoid converting between string and []byte again and again.
  • Pass small structs by value, so they can stay on the stack.
  • Avoid fmt.Sprintf in very hot code, and use strconv instead.
package main

import (
    "fmt"
    "testing"
)

func withoutSize(n int) []int {
    var s []int
    for i := 0; i < n; i++ {
        s = append(s, i)
    }
    return s
}

func withSize(n int) []int {
    s := make([]int, 0, n) // one allocation up front
    for i := 0; i < n; i++ {
        s = append(s, i)
    }
    return s
}

func main() {
    a := testing.AllocsPerRun(100, func() { withoutSize(1000) })
    b := testing.AllocsPerRun(100, func() { withSize(1000) })
    fmt.Println("pre-sized uses fewer allocations:", b < a, "| pre-sized allocs:", b)
}
pre-sized uses fewer allocations: true | pre-sized allocs: 1

Q136. How would you structure a large Go project?

There is no single official layout, but most large Go services follow a similar shape.

myapp/
  cmd/
    api/main.go        // one folder per binary
    worker/main.go
  internal/
    orders/            // one package per business area
    payments/
    platform/          // shared helpers: db, logging, config
  api/                 // OpenAPI or .proto files
  migrations/
  go.mod

Here are the main rules. Keep main.go small, so it only wires things together. Group code by business feature, not by technical layer. Put private code in internal. Avoid a giant utils package, and keep packages small with clear names.

Q137. How do you shut down an HTTP server gracefully?

A graceful shutdown stops taking new requests, lets in-flight requests finish and then closes resources like the database. You listen for SIGINT and SIGTERM, then call srv.Shutdown(ctx) with a timeout.

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()

srv := &http.Server{Addr: ":8080", Handler: mux}
go func() {
    if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
        log.Fatal(err)
    }
}()

<-ctx.Done() // wait for Ctrl+C or a SIGTERM from Kubernetes

shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
    log.Println("forced to stop:", err)
}
db.Close()

ListenAndServe returns http.ErrServerClosed after Shutdown, so do not treat that as an error.

Q138. How do you design a REST API in Go with clean layers?

Split each feature into three simple layers. Each layer has one job, so the code is easy to test and change.

LayerJobKnows about
HandlerRead the HTTP request, validate input, write JSON and status codesHTTP
ServiceBusiness rules, such as “cannot cancel a shipped order”Plain Go types
RepositoryRead and write the databaseSQL or ORM

The handler calls the service, and the service calls the repository through a small interface. So you can test the service with a fake repository and no database. Also, return clear status codes (201 for created, 400 for bad input, 404 for not found) and a consistent error JSON shape.

Q139. What does GOMEMLIMIT do, and how is it different from GOGC?

GOGC sets how often the GC runs, based on heap growth. The default is 100, which means “run when the heap has grown 100% since the last collection”. A higher value means fewer collections but more memory, and a lower value means the opposite.

GOMEMLIMIT, added in Go 1.19, sets a soft limit on total memory, such as GOMEMLIMIT=900MiB. As the program gets close to it, the GC runs more often to stay under the limit. So in a container with a 1 GiB limit, it helps prevent out-of-memory kills. Many teams set GOMEMLIMIT to about 90% of the container limit and leave GOGC at the default.

Q140. What do the unique package and weak pointers give you?

The unique package (Go 1.23) does interning. unique.Make(v) returns a small handle, and equal values always get the same handle. So you can store one copy of a repeated value, such as the same country name across a million records, and compare handles very quickly.

The weak package (Go 1.24) gives weak pointers with weak.Make(p). A weak pointer does not keep its object alive. If nothing else points to the object, the GC can free it, and wp.Value() then returns nil. This is useful for caches that should not stop memory from being freed.

package main

import (
    "fmt"
    "unique"
)

func main() {
    a := unique.Make("India")
    b := unique.Make("India")
    c := unique.Make("Japan")

    fmt.Println(a == b, a == c) // fast handle comparison
    fmt.Println(a.Value())
}
true false
India

Q141. How do you make a Go binary smaller?

Go binaries include the runtime, so even “hello world” is a few megabytes. You can shrink them in a few ways.

CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o app ./cmd/api
  • -ldflags="-s -w" removes the symbol table and debug info.
  • -trimpath removes your local file paths from the binary.
  • CGO_ENABLED=0 gives a static binary that runs in a tiny scratch or distroless Docker image.
  • Remove unused dependencies, because each one adds code.

Tools like UPX can compress the binary further, but startup gets slower and some security scanners flag it. So most teams stop at the flags above.

Q142. gRPC or REST: when would you choose each in Go?

Both work well in Go. The choice depends on who calls your service.

FeatureREST (JSON over HTTP)gRPC (Protobuf over HTTP/2)
Best forPublic APIs, browsers, simple toolsService-to-service calls
SpeedGoodFaster, smaller messages
ContractOptional (OpenAPI)Required .proto file
StreamingLimitedBuilt in, both directions
Easy to test by handYes, with curlNeeds tools like grpcurl

So a common setup is REST for the frontend and partners, and gRPC between internal Go services. See our Go gRPC interview questions for more.

Q143. How do you manage configuration and secrets in a Go service?

Keep configuration out of the code, as the twelve-factor app style suggests. Read settings from environment variables or a config file at startup, put them into one Config struct, check required values and stop with a clear error if something is missing.

type Config struct {
    Port        string
    DatabaseURL string
}

func LoadConfig() (Config, error) {
    cfg := Config{
        Port:        getEnv("PORT", "8080"),
        DatabaseURL: os.Getenv("DATABASE_URL"),
    }
    if cfg.DatabaseURL == "" {
        return Config{}, errors.New("DATABASE_URL is required")
    }
    return cfg, nil
}

For secrets, such as database passwords and API keys, use a secret manager like Vault, AWS Secrets Manager or Kubernetes Secrets. Never commit secrets to Git, and never print them in logs.

Scenario Go Interview Questions with Answers

For each scenario, explain what you would check first, and why. Interviewers care about your steps, not just the final answer, so these answers follow a clear “check, find, fix” order.

Q144. A Go service slowly uses more and more memory. How do you find the cause?

First, confirm it is a real leak and not normal growth. Watch the heap size and goroutine count over a few hours in your metrics. If memory keeps rising and never drops after GC, something is holding on to it.

Next, take two heap profiles some time apart and compare them.

curl -o heap1.prof http://localhost:6060/debug/pprof/heap
# wait 30 minutes
curl -o heap2.prof http://localhost:6060/debug/pprof/heap
go tool pprof -base heap1.prof heap2.prof   # shows what grew

Common causes are a cache or map with no size limit or expiry, goroutine leaks, slices that keep a big array alive (for example small := big[:10]), unclosed response bodies or rows, and timers that are never stopped. Fix the cause, then add a limit, such as an LRU cache with a maximum size.

Q145. Response times jumped after a deploy. How do you find the slow code?

First, check what changed. Compare the new release with the old one: code, dependencies, config and database migrations. If users are hurting, roll back first and investigate after.

Then look at the data. Check which endpoints got slower in your p95 and p99 latency metrics, and use distributed traces to see which step takes the extra time, such as a database query or an outside API. Next, take a 30-second CPU profile from a running pod with pprof and look at the flame graph for new hot functions.

Common causes are a missing database index after a migration, an N+1 query, a new call to a slow service without a timeout, extra logging in a hot loop, or a smaller connection pool. Finally, add a benchmark or a load test so the same problem is caught before the next deploy.

Q146. A program hangs forever under load. How do you debug it?

A hang usually means goroutines are stuck waiting on a channel, a lock or a network call. So first, get a dump of all goroutines while it is stuck.

  • With pprof: open /debug/pprof/goroutine?debug=2 to see every goroutine and the line it is waiting on.
  • Without pprof: send SIGQUIT (Ctrl+\ in a terminal), and Go prints all goroutine stacks before exiting.

Then look for many goroutines blocked at the same line. Typical causes are a channel send with no receiver, a mutex that was locked but never released, two locks taken in a different order (a deadlock), a full connection pool, or an HTTP call with no timeout. Fix the cause, add timeouts with context everywhere and run tests with -race.

Q147. You must process one million records quickly. How do you design it?

Do not load everything into memory, and do not start one million goroutines. Instead, build a streaming pipeline with a fixed number of workers.

  1. First, read records in a stream, such as a CSV with bufio.Scanner or a database cursor, and send them into a buffered channel.
  2. Next, start a worker pool sized to the bottleneck, for example runtime.NumCPU() workers for CPU work, or more for I/O work.
  3. Then batch writes, such as inserting 500 rows per query or using PostgreSQL COPY, because one query per record is slow.
  4. Also, collect errors without stopping everything, and log failed record IDs for a retry.
  5. Finally, make the job restartable by saving progress, such as the last processed ID.
package main

import (
    "fmt"
    "sync"
)

func main() {
    records := make(chan int, 100)
    var processed sync.Map
    var wg sync.WaitGroup

    for w := 0; w < 4; w++ { // fixed number of workers
        wg.Add(1)
        go func() {
            defer wg.Done()
            batch := make([]int, 0, 250)
            flush := func() {
                for _, r := range batch {
                    processed.Store(r, true) // stands in for one bulk insert
                }
                batch = batch[:0]
            }
            for r := range records {
                batch = append(batch, r)
                if len(batch) == cap(batch) {
                    flush()
                }
            }
            flush() // write the last small batch
        }()
    }

    for id := 1; id <= 1_000_000; id++ { // stream records in
        records <- id
    }
    close(records)
    wg.Wait()

    count := 0
    processed.Range(func(_, _ any) bool { count++; return true })
    fmt.Println("records processed:", count)
}
records processed: 1000000

Measure the speed, then tune the number of workers and the batch size to what the database can take.

Q148. Two goroutines update the same map and the app crashes. How do you fix it?

The crash is fatal error: concurrent map writes, because Go maps are not safe for writes from several goroutines. First, confirm it with go test -race or go run -race, which shows the exact lines.

Then pick a fix. The usual one is to put a sync.Mutex (or sync.RWMutex if reads are much more common) next to the map and lock around every read and write. Another option is to give the map to one goroutine and send it updates through a channel. sync.Map also works, but it suits only special cases like caches written once and read many times.

package main

import (
    "fmt"
    "sync"
)

type SafeCounter struct {
    mu     sync.Mutex
    counts map[string]int
}

func (c *SafeCounter) Inc(key string) {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.counts[key]++
}

func main() {
    c := SafeCounter{counts: map[string]int{}}
    var wg sync.WaitGroup
    for i := 0; i < 100; i++ {
        wg.Add(2)
        go func() { defer wg.Done(); c.Inc("orders") }()
        go func() { defer wg.Done(); c.Inc("payments") }()
    }
    wg.Wait()
    fmt.Println(c.counts["orders"], c.counts["payments"])
}
100 100

Q149. Goroutine count keeps growing in production. How do you find the leak?

First, confirm the trend with a metric of runtime.NumGoroutine(), which Prometheus Go clients export as go_goroutines. A healthy service goes up and down with traffic, while a leak only goes up.

Next, open /debug/pprof/goroutine?debug=1. It groups goroutines by stack, so the leak shows up as one stack with thousands of copies. Then read that line of code and ask why the goroutine never ends.

Typical causes are a goroutine sending on a channel after the receiver gave up on a timeout, a for loop that never checks ctx.Done(), HTTP calls with no timeout, and tickers that are never stopped. Fix it by giving every goroutine an exit path, such as a cancelled context or a buffered channel, and add goleak checks to your tests.

Q150. Your service must handle a sudden ten times traffic spike. What do you change?

First, find the bottleneck under load, because scaling the wrong part does not help. Run a load test and watch CPU, memory, database connections and p99 latency.

Then make changes in layers.

  • Scale out: keep the service stateless and add pods with the Kubernetes Horizontal Pod Autoscaler.
  • Cache: put hot reads in Redis or a small in-memory cache, and use a CDN for static content.
  • Protect the database: add read replicas, tune the connection pool and add missing indexes.
  • Move slow work to a queue: send emails and reports to background workers.
  • Protect yourself: add rate limits, timeouts and circuit breakers, and shed low-priority traffic with HTTP 503 when overloaded.
  • Tune Go: set GOMEMLIMIT, check GOMAXPROCS matches the CPU limit, and profile the hottest endpoints.

Finally, test the new setup at more than ten times the normal load, and add alerts so you see the next spike early. Our system design interview questions cover these patterns in detail.

Hands-On Go Interview Questions Practice

Interviewers love “what does this print?” questions. Here is one program that tests slices, maps and defer together. It covers questions 28, 29, 36 and 49.

package main

import "fmt"

func main() {
    // Slices: b shares the same array as a while it has room.
    a := make([]int, 3, 4) // len 3, cap 4: [0 0 0]
    b := append(a, 9)      // fits in the spare slot, so b uses a's array
    b[0] = 7               // this also changes a[0]
    fmt.Println(a, b)

    // Maps: reading a missing key gives the zero value.
    stock := map[string]int{"pen": 5}
    count, found := stock["book"]
    fmt.Println(count, found)

    // defer: calls run in reverse order when main returns.
    for i := 1; i <= 3; i++ {
        defer fmt.Println("deferred", i)
    }
    fmt.Println("end of main")
}
[7 0 0] [7 0 0 9]
0 false
end of main
deferred 3
deferred 2
deferred 1

Because a had spare capacity, append wrote into the same array, so changing b[0] also changed a[0]. Reading a missing map key returns 0, and the second value tells you the key was not found. Finally, the three deferred calls run after “end of main”, newest first.

Next, here is the most asked live coding task: add up numbers using several goroutines. It covers questions 79, 82 and 88.

package main

import (
    "fmt"
    "sync"
)

// sumPart adds up one part of the slice and sends the result on a channel.
func sumPart(numbers []int, results chan<- int, wg *sync.WaitGroup) {
    defer wg.Done() // tell the WaitGroup this worker is finished
    total := 0
    for _, n := range numbers {
        total += n
    }
    results <- total
}

func main() {
    numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    results := make(chan int, 2) // room for both results, so no worker blocks
    var wg sync.WaitGroup

    half := len(numbers) / 2
    wg.Add(2)
    go sumPart(numbers[:half], results, &wg) // first half: 1 to 5
    go sumPart(numbers[half:], results, &wg) // second half: 6 to 10

    wg.Wait()      // wait for both goroutines
    close(results) // no more values will be sent

    grandTotal := 0
    for partial := range results {
        grandTotal += partial
    }
    fmt.Println("total:", grandTotal)
}
total: 55

Each goroutine adds up half of the slice and sends its result into a buffered channel. The WaitGroup waits until both are done, then main closes the channel and adds up the partial totals. In Go 1.25 and later, you can also write wg.Go(func() { … }), which calls Add and Done for you.

Common Mistakes in Go Interview Questions

  • Saying Go has no pointers: it does, but it has no pointer arithmetic.
  • Forgetting that slices share arrays: always explain length, capacity and append.
  • Writing to a map from many goroutines: mention a mutex every time.
  • Returning a typed nil as an error: return a plain nil instead.
  • Starting goroutines with no way to stop them: use context or a done channel to avoid leaks.

Best Practices for Answering Go Interview Questions

  • Give a one-line definition first, then a small code example.
  • Say “it depends” with reasons, such as mutex vs channel, then pick one.
  • Mention the tools, such as go vet, the race detector and pprof.
  • Keep code idiomatic: short names in small scopes, errors checked right away, gofmt style.
  • Use real numbers from your work, such as requests per second or memory saved.

Practice Task

To practise these Go interview questions, write a small URL checker. It should take five URLs, check them at the same time with goroutines, stop each check after two seconds with context.WithTimeout, and print the status for each. Hint: use a WaitGroup and a results slice indexed by position, so the output order stays the same.

Official Resources

Quick Recap

  • Go interview questions focus on basics, slices and maps, interfaces, errors and concurrency.
  • Slices share arrays until append needs more room, and maps are not safe for concurrent writes.
  • Interfaces are implemented implicitly, and a typed nil inside an interface is not nil.
  • Goroutines are cheap, channels pass data, and mutexes protect shared state.
  • Use context for cancellation, and the race detector and pprof to find problems.
  • Every one of the 150 questions now has a full answer, with runnable code for most of them.
  • Practise “what does this print?” programs, because they are very common.

What’s Next?

Now go deeper, one topic at a time. Start with Go Basics Interview Questions for Freshers, then follow the 8-week plan in all interview questions with a study path. For live coding practice, use the Go tricky output programs.