Level: IntermediateInterview

Golang Questions and Answers: 140 Interview Q&A for 2026

Updated 124 min read
Golang Questions and Answers featured image: 140 corrected questions with tested code

Golang questions and answers in this post cover everything interviewers ask most, from basic syntax to goroutines, REST APIs, microservices and system design. You get 140 questions in one place, each with a clear answer, and many with code you can run.

This is a fully rewritten, corrected and reorganised version of our earlier Go Lang interview questions and answers post. For a shorter list with the top answers only, see Go interview questions. For a full study plan, use all interview questions with a study path.

What Is New in These Golang Questions and Answers?

We checked all the Golang questions and answers from the old post. So you can trust this version for real interviews.

  • Clean numbering: questions now run from Q1 to Q140 in one format, grouped by topic.
  • Fixed code: broken quotes and formatting are gone, and every full program was run with its real output shown.
  • Corrected answers: wrong or outdated points were fixed, for example Go has no === operator, and new and init are not keywords.
  • Up to date: answers match Go 1.27, including loop variables from Go 1.22, iterators from Go 1.23 and wg.Go from Go 1.25.
  • No duplicates: questions that were asked twice in the old post are merged into one better answer.

How to Use These Golang Questions and Answers

Do not read all 140 answers in one sitting. Instead, follow these steps.

  1. First, pick the section that matches your next interview round.
  2. Next, cover the answer and try to say it out loud in two or three sentences.
  3. Then, run the code examples yourself and change them a little.
  4. Finally, mark the questions you missed and repeat them after a few days.
Golang questions and answers diagram showing the eight topic sections from basics to system design
The questions move from Go basics and data structures to concurrency, performance, web APIs and system design.

The table below shows the sections and where each one starts.

SectionTopicsQuestions
1Basics and syntaxQ1 to Q22
2Arrays, slices, maps and stringsQ23 to Q32
3Functions, structs and interfacesQ33 to Q48
4Error handlingQ49 to Q51
5Goroutines and concurrencyQ52 to Q83
6Memory, GC and performanceQ84 to Q93
7Web, REST APIs and securityQ94 to Q114
8Microservices, system design and toolsQ115 to Q140

Golang Questions and Answers on Basics and Syntax

These Golang questions and answers cover the core building blocks of Go. If you are new to the language, start here because every later topic builds on them.

Go (often called Golang) is an open-source programming language created at Google. It was designed for simplicity, fast compilation and easy concurrency. Today it is a top choice for cloud services, APIs and command-line tools.

Here are the main reasons developers like it.

  • Simple syntax with only 25 keywords, so code is easy to read.
  • Compiled to native machine code, so programs run fast.
  • Built-in concurrency with goroutines and channels.
  • Automatic garbage collection, so you do not free memory by hand.
  • A strong standard library for HTTP, JSON, testing and more.
  • A single static binary that is easy to ship in Docker images.

Q2. What are pointers in Go?

A pointer is a variable that stores the memory address of another variable. So instead of holding the value itself, it points to where the value lives in memory. The type *T means “pointer to a value of type T”.

You use two operators with pointers.

  • &x gives you the address of x.
  • *p reads or changes the value that p points to. This is called dereferencing.

Here is a small program that changes a value through a pointer.

package main

import "fmt"

func main() {
    x := 10   // a normal int variable
    p := &x   // p holds the address of x (type *int)

    fmt.Println("x =", x)
    fmt.Println("*p =", *p) // read the value through the pointer

    *p = 20 // change x through the pointer
    fmt.Println("x after change =", x)
    fmt.Println("p points to x:", p == &x)
}
x = 10
*p = 10
x after change = 20
p points to x: true

Go pointers are safer than C pointers. For example, Go has no pointer arithmetic, so you cannot move a pointer to a random address. The zero value of a pointer is nil, and dereferencing a nil pointer causes a panic.

Q3. What is the difference between new() and make()?

Both are built-in functions, but they do different jobs. new(T) allocates memory for any type, sets it to the zero value and returns a pointer *T. make works only for slices, maps and channels, and it returns a ready-to-use value, not a pointer.

newmake
Works with any typeWorks only with slice, map and channel
Returns a pointer (*T)Returns the value itself (T)
Memory is set to the zero valueSets up the internal data structure
package main

import "fmt"

func main() {
    // new returns a pointer to a zeroed int
    count := new(int)
    *count = 5
    fmt.Println("count:", *count)

    // make builds a usable map and slice
    ages := make(map[string]int)
    ages["Asha"] = 30
    scores := make([]int, 3, 10) // length 3, capacity 10

    fmt.Println("ages:", ages)
    fmt.Println("scores:", scores, "len:", len(scores), "cap:", cap(scores))
}
count: 5
ages: map[Asha:30]
scores: [0 0 0] len: 3 cap: 10

Q4. What are packages in Go?

A package is a group of Go files in the same folder that are compiled together. Packages help you organise code and reuse it across projects. Every Go file starts with a package line that names its package.

The package main is special because it builds an executable program, and it must have a func main(). Other packages are libraries. Also, only names that start with a capital letter (like Println) are exported and visible to other packages.

package main

import (
    "fmt"
    "strings"
)

func main() {
    // strings and fmt are packages from the standard library
    fmt.Println(strings.ToUpper("hello from package main"))
}
HELLO FROM PACKAGE MAIN

Q5. Can Go functions return multiple values?

Yes. A Go function can return two or more values, and this is used everywhere in Go. The most common pattern returns a result plus an error, so the caller can check if something went wrong.

package main

import (
    "errors"
    "fmt"
)

// divide returns the result and an error if b is zero
func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}

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

    _, err = divide(5, 0)
    fmt.Println("error:", err)
}
5 <nil>
error: cannot divide by zero

Q6. What are variadic functions, and how do you return multiple values from a variadic function?

A variadic function accepts any number of arguments of one type. You write it with three dots, like nums ...int. Inside the function, nums is simply a slice of int.

You can mix a variadic parameter with multiple return values freely. Keep these rules in mind.

  1. Only the last parameter can be variadic.
  2. List the return values in parentheses, and you can give them names.
  3. The caller receives the results as separate variables.
package main

import "fmt"

// sumAndAvg returns both the sum and the average of any number of ints.
func sumAndAvg(nums ...int) (sum int, avg float64) {
    for _, n := range nums {
        sum += n
    }
    if len(nums) > 0 {
        avg = float64(sum) / float64(len(nums))
    }
    return // named results sum and avg are returned
}

func main() {
    s, a := sumAndAvg(3, 5, 7, 9)
    fmt.Println("sum:", s, "avg:", a)

    // pass an existing slice with values...
    values := []int{10, 20}
    s, a = sumAndAvg(values...)
    fmt.Println("sum:", s, "avg:", a)

    // calling with no arguments gives an empty slice
    s, a = sumAndAvg()
    fmt.Println("sum:", s, "avg:", a)
}
sum: 24 avg: 6
sum: 30 avg: 15
sum: 0 avg: 0
TopicTip
Named vs unnamed resultsNamed results allow a bare return. Unnamed results need return v1, v2.
Zero argumentsA call with no arguments gives an empty slice, so check len(nums) if needed.
ForwardingTo pass a slice into a variadic function, add ... after it, like f(vals...).
PerformanceThe arguments are packed into a slice. In very hot loops, passing a slice directly can be cheaper.

Q7. What is dependency management in Go?

Go manages dependencies with modules. A module is described by a go.mod file, which lists the module path, the Go version and the required packages. Also, a go.sum file stores checksums so builds are safe and repeatable.

Here are the commands you use most often.

go mod init example.com/app      # start a new module
go get github.com/google/uuid    # add or upgrade a dependency
go mod tidy                      # add missing and remove unused dependencies
go list -m all                   # list every module in the build

Since Go 1.24, you can also track tool dependencies in go.mod with go get -tool. So the whole team uses the same versions of tools like linters.

Q8. Why do we use the underscore (_) in Go?

The underscore is called the blank identifier. You can assign a value to it, but you can never read from it. This matters because Go does not allow unused variables or unused imports, so _ lets you throw away values you do not need.

Use caseExample
Ignore an extra return value_, err := someFunc()
Ignore the loop index or valuefor _, v := range items
Import a package only for its side effectsimport _ "github.com/lib/pq"
Check at compile time that a type implements an interfacevar _ Shape = (*Circle)(nil)
Ignore a result on purpose_ = file.Close()
package main

import "fmt"

func main() {
    fruits := []string{"apple", "banana", "cherry"}

    // we do not need the index, so we use _
    for _, fruit := range fruits {
        fmt.Println(fruit)
    }

    // Println returns (int, error); keep only the byte count
    n, _ := fmt.Println("Hello")
    fmt.Println("bytes written:", n)
}
apple
banana
cherry
Hello
bytes written: 6

Q9. What is the difference between declaring and initializing a variable in Go?

Declaring a variable tells the compiler that the variable exists and what type it has. Initializing it means giving it a starting value. In Go, a declared variable without a value is never empty, because it always gets the zero value of its type.

You can declare and initialize in a few ways.

  • var count int declares only, so count is 0.
  • var name string = "Go" declares and initializes together.
  • city := "Pune" is the short form. It works only inside functions, and Go infers the type.
package main

import "fmt"

func main() {
    var count int          // declaration only, gets zero value 0
    var name string = "Go" // declaration with initialization
    city := "Pune"         // short declaration, type is inferred

    fmt.Println(count, name, city)

    count = 42 // assignment later
    fmt.Println(count)
}
0 Go Pune
42

Q10. Can we pass parameters to main() in Go?

No. The main function cannot take parameters, and it cannot return a value. Instead, you read command-line arguments from os.Args, which is a slice of strings.

os.Args[0] is the program path, and os.Args[1:] holds the real arguments. For example, you could run go run . hello world.

package main

import (
    "fmt"
    "os"
)

func main() {
    args := os.Args[1:] // skip the program name
    fmt.Println("number of args:", len(args))
    fmt.Println("args:", args)

    if len(args) > 0 {
        fmt.Println("first arg:", args[0])
    }
}
number of args: 2
args: [hello world]
first arg: hello

For named options like -port=8080, use the flag package from the standard library. Also, to set an exit code, call os.Exit(code) instead of returning from main.

Q11. What is GOROOT in Go?

GOROOT is the folder where Go itself is installed. It holds the compiler, the tools and the standard library source. So when you import fmt, Go finds it under GOROOT.

You rarely need to set GOROOT yourself, because the go command works it out from its own location. You can check the value with this command.

go env GOROOT

Do not confuse it with GOPATH. GOPATH is your workspace, and it stores the module cache and installed binaries (by default $HOME/go).

Q12. What is a zero value in Go?

A zero value is the default value Go gives a variable when you declare it without a value. This means Go has no uninitialized variables, so you never read random memory.

TypeZero value
int, float64 and other numbers0
boolfalse
string"" (empty string)
pointer, slice, map, channel, function, interfacenil
structevery field set to its own zero value
package main

import "fmt"

type User struct {
    Name   string
    Age    int
    Active bool
}

func main() {
    var n int
    var ok bool
    var s string
    var nums []int
    var u User

    fmt.Println(n, ok, s == "", nums == nil)
    fmt.Printf("%+v\n", u)
}
0 false true true
{Name: Age:0 Active:false}

Q13. Why is Go fast?

Go is fast both to build and to run. First, it compiles ahead of time to native machine code, so there is no interpreter or virtual machine. Next, its simple grammar and its dependency rules make compilation very quick.

Here are the main reasons.

  • Static typing lets the compiler produce efficient code.
  • Goroutines are lightweight, so a program can run many thousands of them.
  • The garbage collector is concurrent with very short pauses.
  • The runtime is small, so programs start quickly.
  • Structs and arrays are laid out in memory compactly, which is friendly to CPU caches.

Q14. What is the difference between the == and === operators in Go?

Go has no === operator. If you write === in Go code, the compiler gives a syntax error. The === operator comes from JavaScript, where it means strict equality without type conversion.

In Go, you only use == and !=. Because Go is strongly typed, == never converts types for you. So comparing an int with a string does not compile at all, and that is safer than JavaScript’s loose ==.

package main

import "fmt"

type Point struct {
    X, Y int
}

func main() {
    a, b := 5, 5
    fmt.Println(a == b) // same type, same value

    fmt.Println("go" == "Go") // strings are compared byte by byte

    p1 := Point{1, 2}
    p2 := Point{1, 2}
    fmt.Println(p1 == p2) // structs compare field by field

    // fmt.Println(5 == "5") would not compile: mismatched types
}
true
false
true

For reference, this is how the two operators behave in JavaScript.

5 == "5"    // true, the string is converted to a number
5 === "5"   // false, the types are different

Slices, maps and functions cannot be compared with == in Go, except against nil. To compare two slices, use slices.Equal from the standard library.

Q15. Are there classes in Go?

No, Go does not have classes or inheritance. Instead, you get the same results with a few simple tools.

  • Structs hold the data.
  • Methods attached to a type give it behaviour.
  • Interfaces describe behaviour, and types satisfy them automatically.
  • Embedding and composition let you reuse code.
package main

import "fmt"

// User is like a class with fields
type User struct {
    Name string
    Age  int
}

// Greet is a method on User
func (u User) Greet() string {
    return "Hi, I am " + u.Name
}

// Birthday uses a pointer receiver so it can change the User
func (u *User) Birthday() {
    u.Age++
}

func main() {
    u := User{Name: "Smita", Age: 25}
    fmt.Println(u.Greet())
    u.Birthday()
    fmt.Println("new age:", u.Age)
}
Hi, I am Smita
new age: 26

Q16. What are the categories of data types in Go?

Go data types are usually grouped into four categories for learning. The Go specification itself does not use the word “reference type”, but the grouping is still helpful.

CategoryTypes
Basicint, float64, complex128, string, bool, byte, rune
Composite (aggregate)array, struct
Reference-likepointer, slice, map, channel, function
Interfaceinterface types such as error or any

The reference-like types hold a pointer to shared data inside them. So when you copy a slice or a map, both copies still see the same underlying data. However, Go always passes arguments by value, even for these types.

Q17. Can a class call another class inside it in Go?

Go has no class keyword, so there is no “class within a class”. Go prefers composition over inheritance. You still have three simple ways to make one type use another.

  1. Composition: one struct has another struct as a named field.
  2. Embedding: you put a struct inside another without a field name, so its fields and methods are promoted. This feels a bit like inheritance, but it is not.
  3. Interfaces: a struct holds an interface field, so you can swap the real type later. This works well in large projects and in tests.
package main

import "fmt"

type Engine struct {
    Power int
}

func (e Engine) Start() string {
    return fmt.Sprintf("engine with %d HP started", e.Power)
}

// Car embeds Engine, so Car gets the Start method
type Car struct {
    Engine
    Brand string
}

func main() {
    c := Car{Engine: Engine{Power: 150}, Brand: "Tata"}
    fmt.Println(c.Brand, c.Start()) // promoted method
    fmt.Println("power:", c.Power)  // promoted field
}
Tata engine with 150 HP started
power: 150

Q18. What is an anonymous struct in Go?

An anonymous struct is a struct without a type name. You declare it and fill it in one step, and it exists only where you write it. So it is handy for short-lived data.

package main

import "fmt"

func main() {
    // no "type Person struct" is needed
    person := struct {
        Name string
        Age  int
    }{
        Name: "Smita",
        Age:  25,
    }

    fmt.Println(person.Name, person.Age)
}
Smita 25

You often use anonymous structs in these cases.

  • Temporary data inside one function.
  • Shaping a JSON response quickly.
  • Table-driven tests, where each test case is a small struct.
  • One-time values where a named type would only add noise.

Q19. What is the difference between new and init in Go?

Neither one is a keyword. new is a built-in function, and init is a special function name. They have very different jobs.

new(T) allocates memory for a type, sets it to the zero value and returns a pointer to it. You call it yourself whenever you need it.

init() is a function that Go runs for you, before main() starts. It runs when its package is initialized.

newinit
Built-in functionSpecial function you write
You call it in your codeGo calls it automatically, you cannot call it
Takes a type, returns a pointerTakes no arguments, returns nothing
Used for allocationUsed for package setup

A file can have several init functions, and they run in the order they appear.

package main

import "fmt"

var config map[string]string

// init runs automatically before main
func init() {
    config = map[string]string{"env": "dev"}
    fmt.Println("init: config ready")
}

func main() {
    fmt.Println("main: env =", config["env"])

    p := new(int) // pointer to a zeroed int
    fmt.Println("new int value:", *p)
}
init: config ready
main: env = dev
new int value: 0

Q20. What is the difference between a package and a module?

A package is a folder of Go files that share the same package name and are compiled together. A module is a versioned collection of related packages. So a module can hold many packages, and each package lives in one folder.

A module is defined by its go.mod file at the root. That file sets the module path, the Go version and the dependencies.

module example.com/shop

go 1.27

require github.com/google/uuid v1.6.0
PackageModule
One folder of .go filesA tree of packages with a go.mod file
Imported by its path, like example.com/shop/cartVersioned and downloaded as one unit
Unit of code organisationUnit of release and dependency management

Q21. How do you compile Go code on Windows and Linux?

You use go build on both systems. It creates a binary for the current operating system, such as app.exe on Windows or app on Linux.

go build -o app .

Go also cross-compiles easily. You set two environment variables, GOOS for the operating system and GOARCH for the CPU type.

# On Linux or macOS, build a Windows binary
GOOS=windows GOARCH=amd64 go build -o app.exe .
# On Windows PowerShell, build a Linux binary
$env:GOOS="linux"
$env:GOARCH="amd64"
go build -o app .

You can list every supported target with go tool dist list. If your code uses cgo, cross-compiling needs a C toolchain for the target, so many teams set CGO_ENABLED=0 for simple static builds.

Q22. What is variable scope in Go?

Variable scope is the part of the program where a variable can be used. Go uses block scope, so a variable declared inside { } exists only inside those braces.

These are the main levels of scope.

  • Universe scope holds built-in names like int, len and true.
  • Package scope covers variables declared outside any function. Every file in the package can use them.
  • File scope applies to imports, which are visible only in the file that imports them.
  • Function and block scope cover variables declared inside a function, an if, a for or a switch.
package main

import "fmt"

var appName = "demo" // package scope

func main() {
    count := 1 // function scope

    if count > 0 {
        message := "inside if" // block scope
        count := 99            // shadows the outer count
        fmt.Println(message, count)
    }

    fmt.Println(appName, count) // outer count is unchanged
}
inside if 99
demo 1

Watch out for shadowing, where an inner := creates a new variable with the same name. Linters such as golangci-lint with the shadow check can warn you about it.

Golang Questions and Answers on Arrays, Slices, Maps and Strings

Arrays, slices, maps and strings are the data types you use every day in Go. These Golang questions and answers cover how they work, how they differ and a few common patterns built on them.

Q23. What are slices in Go?

A slice is a dynamic, flexible view over an underlying array. It does not store the data itself. Instead, it holds three things: a pointer to the array, a length and a capacity.

  • A slice can grow with the built-in append function.
  • It is always backed by an array that Go manages for you.
  • Its length and capacity are read with len and cap.

Here is a small program that creates a slice and grows it.

package main

import "fmt"

func main() {
    // A slice literal creates the backing array for you
    nums := []int{1, 2, 3}

    // append adds an element and returns the updated slice
    nums = append(nums, 4)

    fmt.Println(nums)
    fmt.Println("length:", len(nums))

    // Slicing creates a new view over the same array
    firstTwo := nums[:2]
    fmt.Println(firstTwo)
}
[1 2 3 4]
length: 4
[1 2]

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

An array has a fixed size, and that size is part of its type. So [3]int and [4]int are two different types. A slice has a dynamic size and works as a view into an underlying array.

FeatureArraySlice
SizeFixed at compile time, for example [3]intDynamic, can grow with append, for example []int
Declarationvar a [3]intvar s []int
Size in typeYes, the length is part of the typeNo, any length has the same type
MemoryHolds the elements directlyHolds a pointer, length and capacity
Passing to a functionThe whole array is copiedThe slice header is copied, but it shares the same array
Can grow?NoYes, with append
Zero valueAn array full of zero valuesnil
Use in real codeRareVery common

Go always passes arguments by value. When you pass a slice, Go copies only the small slice header. Because the copy points to the same array, changes to elements are visible to the caller. However, an append inside the function may create a new array, so the caller will not see the new length.

package main

import "fmt"

func changeArray(a [3]int) {
    a[0] = 100 // changes only the local copy
}

func changeSlice(s []int) {
    s[0] = 100 // changes the shared backing array
}

func main() {
    arr := [3]int{1, 2, 3}
    sl := []int{1, 2, 3}

    changeArray(arr)
    changeSlice(sl)

    fmt.Println("array:", arr)
    fmt.Println("slice:", sl)
}
array: [1 2 3]
slice: [100 2 3]

Q25. What is the difference between len and cap?

len gives the number of elements currently in the slice. These are the elements you can read with an index. It is never negative and never larger than the capacity.

cap gives the number of elements the backing array can hold, counted from the start of the slice. So it tells you how far the slice can grow before Go must allocate a bigger array.

  • Length means how many elements are actually in the slice.
  • Capacity means how many elements fit before a reallocation.

When append goes past the capacity, Go allocates a new, larger array and copies the elements over. The exact growth size is an internal detail, so do not depend on it.

package main

import "fmt"

func main() {
    // make creates a slice with length 3 and capacity 5
    s := make([]int, 3, 5)
    fmt.Println(len(s), cap(s))

    // Two more elements still fit in the same array
    s = append(s, 7, 8)
    fmt.Println(len(s), cap(s))
    fmt.Println(s)
}
3 5
5 5
[0 0 0 7 8]

Q26. What are maps in Go?

A map stores key-value pairs. You look up a value by its key, and the lookup is fast on average. Keys must be a comparable type, such as string, int or a struct of comparable fields.

If a key is missing, the map returns the zero value of the value type. So you use the “comma ok” form to check whether a key really exists. Also, the iteration order of a map is not fixed, so sort the keys when you need a stable order.

package main

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

func main() {
    scores := map[string]int{
        "a": 1,
        "b": 2,
    }

    // Check if a key exists with the comma ok idiom
    v, ok := scores["a"]
    fmt.Println(v, ok)

    missing, ok := scores["z"]
    fmt.Println(missing, ok)

    // Sort the keys to get a predictable order
    for _, key := range slices.Sorted(maps.Keys(scores)) {
        fmt.Println(key, scores[key])
    }
}
1 true
0 false
a 1
b 2

Q27. What is the difference between a nil slice and an empty slice?

A nil slice has no backing array, and it equals nil. You get one with var s []int. An empty slice has a backing array of size zero, so it is not nil. You get one with s := []int{} or make([]int, 0).

Both have a length of 0, and both work with len, append and range. The difference shows up in nil checks and in JSON encoding. For example, a nil slice encodes as null, but an empty slice encodes as [].

package main

import (
    "encoding/json"
    "fmt"
)

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

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

    // JSON output differs between the two
    a, _ := json.Marshal(nilSlice)
    b, _ := json.Marshal(emptySlice)
    fmt.Println(string(a), string(b))
}
0 true
0 false
null []

Q28. How do you define a map in Go?

A map is a built-in type that stores key-value pairs. It is similar to a dictionary in Python or an object used as a lookup table in JavaScript. You write the type as map[KeyType]ValueType.

A map declared with var m map[string]int is nil. Reading from a nil map is fine, but writing to it causes a panic. So create the map with make or a literal before you add values.

package main

import "fmt"

func main() {
    ages := make(map[string]int)

    ages["Alice"] = 30
    ages["Bob"] = 25

    // fmt prints maps with keys in sorted order
    fmt.Println(ages)
    fmt.Println(ages["Bob"])

    delete(ages, "Alice")
    fmt.Println(len(ages))
}
map[Alice:30 Bob:25]
25
1

Here are the common map operations.

OperationSyntax or example
Declarevar m map[string]int
Initializem := make(map[string]int)
Literalm := map[string]int{"a": 1}
Add or update a valuem["key"] = value
Read a valuev := m["key"]
Check existencev, ok := m["key"]
Delete a keydelete(m, "key")
Remove all keysclear(m)
Loopfor k, v := range m { ... }

Q29. What is the difference between a rune and a string?

A string is an immutable sequence of bytes. It usually holds UTF-8 text. A rune is an alias for int32, and it holds one Unicode code point, which is roughly one character.

len on a string counts bytes, not characters. So for text with non-English letters, convert to []rune or use utf8.RuneCountInString to count characters. Also, you cannot change a string in place. Instead, convert it to []rune, change the runes, then convert it back.

Featurestringrune
TypeImmutable sequence of bytes, usually UTF-8int32, one Unicode code point
Lengthlen(str) gives byteslen([]rune(str)) gives characters
PurposeFull textA single character
Can you change it?No, strings are immutableA []rune slice can be changed
Useful forSentences, names and other textCharacter processing and Unicode logic
TaskUse
Store or pass textstring
Work with single charactersrune
Count characters in textutf8.RuneCountInString(str) or len([]rune(str))
Change characters, for example case[]rune or the unicode package
package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    word := "héllo"

    fmt.Println("bytes:", len(word))
    fmt.Println("characters:", utf8.RuneCountInString(word))

    // range over a string gives runes, not bytes
    for i, r := range word {
        fmt.Printf("%d %c\n", i, r)
    }

    // Change a character through a []rune copy
    runes := []rune(word)
    runes[0] = 'H'
    fmt.Println(string(runes))
}
bytes: 6
characters: 5
0 h
1 é
3 l
4 l
5 o
Héllo

Q30. Why use a slice instead of an array?

Slices are the normal way to handle collections in Go. You reach for an array only when the size is fixed and known, for example a 16-byte key.

  1. Flexibility. A slice can grow and shrink, but an array cannot.
  2. Efficiency. Slices share the backing array, so slicing does not copy the data.
  3. Simplicity. Built-in tools such as append, copy and the slices package work on slices.
  4. Idiomatic Go. Most standard library functions take and return slices.

The old version of this answer talked about “call by reference”. However, Go has only call by value. When you pass an array, the whole array is copied. When you pass a slice, only its small header is copied, and it still points to the same data. If you need a function to change an array, pass a pointer to it, and that pointer is also copied by value.

Q31. What is the sliding window technique in data structures?

Sliding window is a technique for arrays and strings. You keep a “window” over a range of elements. Then you move the window one step at a time instead of recomputing everything from scratch.

For example, to find the largest sum of any 3 numbers in a row, you add the new element and subtract the element that left the window. So each step costs only a constant amount of work.

package main

import "fmt"

// maxSumOfK returns the largest sum of k consecutive numbers
func maxSumOfK(nums []int, k int) int {
    windowSum := 0
    for i := 0; i < k; i++ {
        windowSum += nums[i]
    }
    best := windowSum

    // Slide the window: add the new element, drop the old one
    for i := k; i < len(nums); i++ {
        windowSum += nums[i] - nums[i-k]
        best = max(best, windowSum)
    }
    return best
}

func main() {
    nums := []int{2, 1, 5, 1, 3, 2}
    fmt.Println(maxSumOfK(nums, 3))
}
9

Q32. Why use the sliding window technique?

It reduces time complexity because it avoids nested loops. A brute force solution often checks every subarray in O(n²) time. With a sliding window, you visit each element a small number of times, so the work drops to O(n).

There are two main types.

  1. Fixed size window. The window size stays the same. For example, find the maximum sum of a subarray of size k.
  2. Variable size window. The window grows and shrinks based on a condition. For example, find the longest substring without repeating characters.

Here is the variable size version for the longest substring problem.

package main

import "fmt"

// longestUnique returns the length of the longest substring
// that has no repeated characters
func longestUnique(s string) int {
    lastSeen := make(map[rune]int)
    start, best := 0, 0
    runes := []rune(s)

    for end, ch := range runes {
        // If ch is inside the window, move the start past it
        if pos, ok := lastSeen[ch]; ok && pos >= start {
            start = pos + 1
        }
        lastSeen[ch] = end
        best = max(best, end-start+1)
    }
    return best
}

func main() {
    fmt.Println(longestUnique("abcabcbb"))
    fmt.Println(longestUnique("bbbbb"))
    fmt.Println(longestUnique("pwwkew"))
}
3
1
3

Golang Questions and Answers on Functions, Structs and Interfaces

Go has no classes, so functions, structs and interfaces do most of the design work. These Golang questions and answers show how they fit together, with small programs you can run.

Q33. What are interfaces in Go?

An interface is a type that lists a set of method signatures. It describes behaviour, not data. Any type that has all those methods satisfies the interface automatically.

  • Implementation is implicit, so you never declare it.
  • There is no implements keyword in Go.
  • Small interfaces, such as io.Reader with one method, are common and easy to reuse.
package main

import "fmt"

// Speaker is any type that can speak
type Speaker interface {
    Speak() string
}

type Dog struct{}
type Cat struct{}

// Dog and Cat satisfy Speaker just by having a Speak method
func (Dog) Speak() string { return "Woof" }
func (Cat) Speak() string { return "Meow" }

func main() {
    animals := []Speaker{Dog{}, Cat{}}
    for _, a := range animals {
        fmt.Println(a.Speak())
    }
}
Woof
Meow

Q34. What is an empty interface?

The empty interface, interface{}, has no methods. Every type has at least zero methods, so a value of any type can be stored in it. Since Go 1.18, any is a built-in alias for interface{}, and you should prefer any in new code.

You lose compile-time type checks when you use any. So, to get the concrete value back, you need a type assertion or a type switch. Also, think about generics first when you only want code that works for many types.

package main

import "fmt"

func main() {
    var anything any

    anything = 42
    fmt.Printf("%v %T\n", anything, anything)

    anything = "hello"
    fmt.Printf("%v %T\n", anything, anything)

    anything = []string{"a", "b"}
    fmt.Printf("%v %T\n", anything, anything)
}
42 int
hello string
[a b] []string

Q35. What is type assertion?

A type assertion pulls the concrete value out of an interface. You write i.(T), where T is the type you expect. If the value is not of type T, the single-value form panics.

So use the safe “comma ok” form when you are not sure. It returns the value and a boolean. When the check fails, you get the zero value of T and false, with no panic.

package main

import "fmt"

func main() {
    var i any = "hello"

    // Single-value form: panics if i is not a string
    s := i.(string)
    fmt.Println(s)

    // Safe form: ok is false instead of a panic
    n, ok := i.(int)
    fmt.Println(n, ok)

    text, ok := i.(string)
    fmt.Println(text, ok)
}
hello
0 false
hello true

Q36. What is a struct?

A struct groups related fields into one type. For example, a User can hold a name, an age and an email together. Structs are value types, so assigning one to another variable copies all its fields.

You can attach methods to a struct. Then you can pass a pointer to it when a function needs to change the original.

package main

import "fmt"

type User struct {
    Name  string
    Age   int
    Email string
}

func main() {
    u := User{Name: "Asha", Age: 28}
    u.Email = "asha@example.com"
    fmt.Printf("%+v\n", u)

    // A pointer lets you change the original struct
    p := &u
    p.Age = 29
    fmt.Println(u.Age)

    // Fields you do not set get their zero values
    var empty User
    fmt.Printf("%+v\n", empty)
}
{Name:Asha Age:28 Email:asha@example.com}
29
{Name: Age:0 Email:}

Q37. Does Go support inheritance?

No, Go does not support classical inheritance. There are no classes, no extends keyword and no type hierarchy. Instead, Go gives you two tools.

  • Composition, where a struct holds other types as fields.
  • Embedding, where a struct includes another type without a field name, so its fields and methods are promoted.

For shared behaviour across different types, you use interfaces. Here, Car embeds Engine and can call Start directly.

package main

import "fmt"

type Engine struct {
    Power int
}

func (e Engine) Start() string {
    return fmt.Sprintf("engine with %d HP started", e.Power)
}

// Car embeds Engine, so Engine's fields and methods are promoted
type Car struct {
    Engine
    Model string
}

func main() {
    c := Car{Engine: Engine{Power: 150}, Model: "Sedan"}
    fmt.Println(c.Model)
    fmt.Println(c.Power)   // promoted field
    fmt.Println(c.Start()) // promoted method
}
Sedan
150
engine with 150 HP started

Q38. What is embedding in Go?

Embedding lets one struct include another type directly, without giving it a field name. The fields and methods of the embedded type are then promoted. So you can call them on the outer struct as if they were its own.

Embedding is composition, not inheritance. A Car that embeds Engine is not an Engine, and you cannot pass a Car where an Engine is expected. However, if the promoted methods satisfy an interface, the outer struct satisfies that interface too.

You can also embed interfaces inside interfaces. For example, io.ReadWriter embeds io.Reader and io.Writer.

// Interface embedding in the standard library
type ReadWriter interface {
    Reader
    Writer
}

Q39. What is defer?

defer schedules a function call to run when the surrounding function returns. It runs even if the function returns early or panics. So it is the standard way to clean up resources.

  • Closing files and network connections.
  • Releasing a mutex with mu.Unlock().
  • Other cleanup tasks, such as stopping a timer.

Deferred calls run in last in, first out order. Also, the arguments of a deferred call are evaluated right away, not when the call finally runs.

package main

import "fmt"

func main() {
    fmt.Println("start")

    for i := 1; i <= 3; i++ {
        defer fmt.Println("deferred", i)
    }

    x := 10
    // x is evaluated now, so this prints 10
    defer fmt.Println("x at defer time:", x)
    x = 20
    fmt.Println("x now:", x)

    fmt.Println("end")
}
start
x now: 20
end
x at defer time: 10
deferred 3
deferred 2
deferred 1

Q40. How do you find out which type of value is stored in an interface, for example int or string?

A single type assertion works when you expect one type. But when the value could be one of many types, a type switch is cleaner. It looks like a normal switch, but it uses i.(type), and inside each case the variable already has that concrete type.

package main

import (
    "fmt"
    "reflect"
)

func describe(i any) string {
    switch v := i.(type) {
    case int:
        return fmt.Sprintf("int with value %d", v)
    case string:
        return fmt.Sprintf("string of length %d", len(v))
    case float64:
        return fmt.Sprintf("float64 with value %.2f", v)
    case nil:
        return "nil value"
    default:
        // %T prints the dynamic type of any value
        return fmt.Sprintf("other type: %T", v)
    }
}

func main() {
    values := []any{42, "hello", 3.14, nil, true}
    for _, v := range values {
        fmt.Println(describe(v))
    }

    // reflect.TypeOf is handy for logging and debugging
    fmt.Println(reflect.TypeOf(3.14))
}
int with value 42
string of length 5
float64 with value 3.14
nil value
other type: bool
float64

Here is a quick comparison of the three ways.

MethodUse caseExample
Type assertionExtract one known typev, ok := i.(string)
Type switchHandle many types cleanlyswitch v := i.(type) { ... }
%T or reflect.TypeOfLogging or generic inspectionfmt.Printf("%T", i)

Q41. What is a wrapper function?

A wrapper function wraps another function to add extra behaviour before, after or around it. You do not change the original code. In Go, a wrapper usually takes a function and returns a new function with the same signature. This is the decorator pattern.

Go has no wrapper classes like Java. Instead, you use functions, closures and sometimes structs that embed another type.

  • Code reuse. You write logging, timing or retries once and apply them to many functions.
  • Separation of concerns. Core logic stays clean, and the extra behaviour lives in the wrapper.
  • Middleware. HTTP middleware in net/http, Gin or Fiber is a wrapper around a handler.
package main

import "fmt"

// withLogging returns a new function that logs around fn
func withLogging(name string, fn func(int, int) int) func(int, int) int {
    return func(a, b int) int {
        fmt.Printf("calling %s(%d, %d)\n", name, a, b)
        result := fn(a, b)
        fmt.Printf("%s returned %d\n", name, result)
        return result
    }
}

func main() {
    add := withLogging("add", func(a, b int) int { return a + b })
    total := add(2, 3)
    fmt.Println("total:", total)
}
calling add(2, 3)
add returned 5
total: 5

Here is the same idea as HTTP middleware with the standard library.

func logRequests(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Println(r.Method, r.URL.Path)
        next.ServeHTTP(w, r) // call the wrapped handler
    })
}

Q42. What is a callback function?

A callback is a function you pass as an argument to another function. The receiving function calls it later, usually after it finishes some work. In other words, you tell the function, “when you are done, call this for me”.

Go functions are first-class values, so callbacks are easy. A callback runs on the same goroutine unless you start a new one. For async work in Go, you usually use goroutines and channels rather than chains of callbacks.

  • Flexibility. Behaviour changes based on which callback you pass.
  • Separation of concerns. The processing logic and the “what to do next” step stay apart.
  • Common uses. You see them in sort.Slice, strings.Map and http.HandleFunc.
package main

import (
    "fmt"
    "strings"
)

// processData takes another function as an argument
func processData(data string, callback func(string)) {
    fmt.Println("Processing:", data)
    callback(data) // call the callback after processing
}

func printResult(result string) {
    fmt.Println("Processed result:", result)
}

func main() {
    processData("Hello Golang", printResult)

    // An anonymous function works as a callback too
    processData("go", func(s string) {
        fmt.Println("Upper:", strings.ToUpper(s))
    })
}
Processing: Hello Golang
Processed result: Hello Golang
Processing: go
Upper: GO

Q43. What is polymorphism, and how do you achieve it in Go using interfaces?

Polymorphism means different types can be used through the same interface, and each type gives its own behaviour. So the same method call can do different things depending on the value behind it.

Go has no classes, but interfaces give you polymorphism. If a type has all the methods of an interface, it satisfies that interface implicitly.

  1. There is no inheritance, only interfaces and methods on types.
  2. Implementation is implicit, with no implements keyword.
  3. The method that runs depends on the dynamic type stored in the interface at runtime.
package main

import (
    "fmt"
    "math"
)

type Shape interface {
    Area() float64
}

type Rectangle struct{ Width, Height float64 }
type Circle struct{ Radius float64 }

func (r Rectangle) Area() float64 { return r.Width * r.Height }
func (c Circle) Area() float64    { return math.Pi * c.Radius * c.Radius }

func main() {
    shapes := []Shape{Rectangle{3, 4}, Circle{2}}

    // The same call runs a different Area method for each type
    for _, s := range shapes {
        fmt.Printf("%T area: %.2f\n", s, s.Area())
    }
}
main.Rectangle area: 12.00
main.Circle area: 12.57

Q44. What is a closure function in Go?

A closure is a function that captures variables from the scope where it was defined. It keeps those variables alive even after the outer function has returned. You can think of it as a function with a memory.

In the example, the inner function remembers count. Each call to counter() creates a new count, so c1 and c2 do not share state.

package main

import "fmt"

func counter() func() int {
    count := 0
    return func() int {
        count++ // count lives on inside the closure
        return count
    }
}

func main() {
    c1 := counter()
    fmt.Println(c1())
    fmt.Println(c1())
    fmt.Println(c1())

    c2 := counter() // separate memory
    fmt.Println(c2())
}
1
2
3
1

Closures and loops were a classic trap in old Go. Since Go 1.22, each loop iteration gets its own copy of the loop variable. This means a closure created inside a for loop now captures the value for that iteration.

Q45. What are generics in Go?

Generics let you write functions and data types that work with many types while keeping type safety. Before Go 1.18, developers used interface{} for this, but they lost compile-time checks and needed type assertions. Generics arrived in Go 1.18, released in March 2022.

  • Type parameters go in square brackets, for example [T any].
  • Constraints limit the allowed types, for example int | float64 or cmp.Ordered.
  • The ~ sign, as in ~int, also allows types whose underlying type is int.
  • Generics give you code reuse with full type safety.
package main

import "fmt"

// Number allows any type whose underlying type is int or float64
type Number interface {
    ~int | ~float64
}

func Sum[T Number](nums []T) T {
    var total T
    for _, n := range nums {
        total += n
    }
    return total
}

// Filter keeps the items for which keep returns true
func Filter[T any](items []T, keep func(T) bool) []T {
    var result []T
    for _, item := range items {
        if keep(item) {
            result = append(result, item)
        }
    }
    return result
}

func main() {
    fmt.Println(Sum([]int{1, 2, 3}))
    fmt.Println(Sum([]float64{1.5, 2.5}))

    evens := Filter([]int{1, 2, 3, 4, 5, 6}, func(n int) bool { return n%2 == 0 })
    fmt.Println(evens)
}
6
4
[2 4 6]

Q46. What is composition in Go?

Composition means building a type out of other types. In Go, you embed structs or interfaces inside a struct, or hold them as named fields. This gives you code reuse and polymorphic behaviour without inheritance.

A related interview question is “Why use an empty struct in Go?”. The empty struct, struct{}, takes zero bytes of memory. So it is ideal when only presence or a signal matters, not the data.

  1. As a map value to build a set, for example map[string]struct{}.
  2. Inside channels as a signal, for example chan struct{} to tell goroutines to stop.
  3. As a placeholder type that only carries methods.
package main

import (
    "fmt"
    "unsafe"
)

func main() {
    fmt.Println("size:", unsafe.Sizeof(struct{}{}))

    // A set of strings, using struct{} as a zero-size value
    seen := map[string]struct{}{}
    for _, lang := range []string{"go", "java", "go"} {
        seen[lang] = struct{}{}
    }
    fmt.Println("unique:", len(seen))

    _, ok := seen["go"]
    fmt.Println("has go:", ok)
}
size: 0
unique: 2
has go: true

The old post also had a coding puzzle here. It asks you to find the letters common to all words, so ["sumita", "amit", "mahesh"] gives [a m]. The program counts letters in the first word, then keeps the smallest count seen in every other word. Finally, it sorts the result so the output is stable.

package main

import (
    "fmt"
    "sort"
)

func commonChars(words []string) []string {
    if len(words) == 0 {
        return []string{}
    }

    // Count letters in the first word
    common := make(map[rune]int)
    for _, ch := range words[0] {
        common[ch]++
    }

    // Keep the minimum count across the other words
    for _, word := range words[1:] {
        counts := make(map[rune]int)
        for _, ch := range word {
            counts[ch]++
        }
        for ch, c := range common {
            common[ch] = min(c, counts[ch])
        }
    }

    // Collect the letters, then sort for a stable order
    var result []string
    for ch, count := range common {
        for i := 0; i < count; i++ {
            result = append(result, string(ch))
        }
    }
    sort.Strings(result)
    return result
}

func main() {
    words := []string{"sumita", "amit", "mahesh"}
    fmt.Println(commonChars(words))
}
[a m]

Q47. What is reflection in Go?

Reflection lets a program inspect and change values whose types are only known at runtime. Go provides it through the reflect package. Normally, types are known at compile time, but sometimes you need more flexibility.

  • Inspecting an unknown type, as JSON encoders and ORMs such as GORM do.
  • Reading struct fields, struct tags and methods dynamically.
  • Writing general tools for logging, validation or data mapping.

The key concepts are listed below.

  1. reflect.TypeOf(x) returns the type of a value.
  2. reflect.ValueOf(x) returns the value itself, wrapped in a reflect.Value.
  3. Kind is the underlying category, such as int, string, slice or struct.
  4. Set methods change a value, but only if it is settable. That means you must reflect on a pointer and call Elem, and struct fields must be exported.

Reflection is slower and less safe than normal code. So prefer interfaces or generics when they can do the job.

package main

import (
    "fmt"
    "reflect"
)

type User struct {
    Name string
    Age  int
}

func main() {
    u := User{Name: "Asha", Age: 30}

    t := reflect.TypeOf(u)
    fmt.Println(t, t.Kind())

    // Loop over the struct fields
    v := reflect.ValueOf(u)
    for i := 0; i < t.NumField(); i++ {
        fmt.Printf("%s %s = %v\n", t.Field(i).Name, t.Field(i).Type, v.Field(i))
    }

    // To change a field, reflect on a pointer and use Elem
    pv := reflect.ValueOf(&u).Elem()
    pv.FieldByName("Age").SetInt(31)
    fmt.Println(u.Age)
}
main.User struct
Name string = Asha
Age int = 30
31

Q48. What is dependency injection in Go?

Dependency injection (DI) is a design pattern where a type receives its dependencies from outside instead of creating them itself. In short, do not build dependencies inside a struct or function, pass them in.

In Go, you usually do this with plain constructor functions and small interfaces. No framework is needed. Because the struct depends on an interface, you can pass a real implementation in production and a fake one in tests. This makes your code loosely coupled, easier to test and easier to maintain.

package main

import "fmt"

// Notifier is the dependency, described as an interface
type Notifier interface {
    Send(to, msg string) error
}

type EmailNotifier struct{}

func (EmailNotifier) Send(to, msg string) error {
    fmt.Printf("email to %s: %s\n", to, msg)
    return nil
}

// FakeNotifier records messages, which is useful in tests
type FakeNotifier struct {
    sent []string
}

func (f *FakeNotifier) Send(to, msg string) error {
    f.sent = append(f.sent, to+": "+msg)
    return nil
}

type OrderService struct {
    notifier Notifier
}

// NewOrderService receives its dependency from outside
func NewOrderService(n Notifier) *OrderService {
    return &OrderService{notifier: n}
}

func (s *OrderService) PlaceOrder(user string) error {
    return s.notifier.Send(user, "your order is placed")
}

func main() {
    real := NewOrderService(EmailNotifier{})
    real.PlaceOrder("asha@example.com")

    fake := &FakeNotifier{}
    test := NewOrderService(fake)
    test.PlaceOrder("test-user")
    fmt.Println("fake sent:", fake.sent)
}
email to asha@example.com: your order is placed
fake sent: [test-user: your order is placed]

Golang Questions and Answers on Error Handling

Go treats errors as normal values that functions return, not as exceptions. These Golang questions and answers show how to create, wrap, check and recover from errors the Go way.

Q49. What are panic and recover in Go?

panic stops the normal flow of a goroutine. When a panic happens, Go runs the deferred functions of the current function, then of its callers, one by one. If nothing stops it, the program crashes and prints a stack trace.

recover is a built-in function that stops a panic. However, it only works when you call it directly inside a deferred function. Outside a deferred function, recover simply returns nil.

package main

import "fmt"

// safeDivide turns a panic into a normal error value
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))
    fmt.Println("program keeps running")
}
5 <nil>
0 recovered: runtime error: integer divide by zero
program keeps running

Use panic only for real bugs or states that should never happen. For expected problems, such as a missing file or bad user input, return an error instead. Also, recover only catches panics in its own goroutine, so a panic in another goroutine still crashes the program.

Q50. What are error wrapping and unwrapping in Go?

Since Go 1.13, you can wrap an error to add context while keeping the original cause. Then the caller can still check what went wrong underneath. This gives you messages that show both where and why an error happened.

To wrap an error, use fmt.Errorf with the %w verb. To look inside the chain, use the errors package.

  • errors.Is(err, target) checks if err or any error it wraps equals target.
  • errors.As(err, &target) finds the first error in the chain of a given type and stores it in target.
  • errors.Unwrap(err) returns the next error in the chain, one layer down.
package main

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

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

func findUser(id int) error {
    if id == 0 {
        return ErrNotFound
    }
    return nil
}

func getUser(id int) error {
    if err := findUser(id); err != nil {
        // wrap the original error with more context
        return fmt.Errorf("getUser failed: %w", err)
    }
    return nil
}

func main() {
    err := getUser(0)
    fmt.Println("error:", err)

    // errors.Is looks through every wrapped layer
    if errors.Is(err, ErrNotFound) {
        fmt.Println("user not found")
    }

    // errors.Unwrap removes one layer
    fmt.Println("cause:", errors.Unwrap(err))

    // errors.As finds an error of a specific type
    _, openErr := os.Open("missing.txt")
    wrapped := fmt.Errorf("load config: %w", openErr)
    var pathErr *os.PathError
    if errors.As(wrapped, &pathErr) {
        fmt.Println("path error on file:", pathErr.Path)
    }
}
error: getUser failed: record not found
user not found
cause: record not found
path error on file: missing.txt

Always prefer errors.Is over err == ErrNotFound, because == fails once the error is wrapped. Also, since Go 1.20 you can wrap several errors at once with errors.Join or with more than one %w in fmt.Errorf.

ActionHow
Wrap (add context)fmt.Errorf("doing X: %w", err)
Check for a specific error valueerrors.Is(err, ErrNotFound)
Get an error of a specific typeerrors.As(err, &pathErr)
Remove one layererrors.Unwrap(err)
Combine several errorserrors.Join(err1, err2)

Q51. What are the common ways to handle errors in Go?

Go has no try and catch. Instead, a function returns an error as its last value, and you check it right away with if err != nil. Here are the patterns you use most often.

First, return the error to the caller. This is the simplest choice when the current function cannot fix the problem.

Next, wrap the error with context, so the final message tells the full story. Interviewers like this pattern because it shows you care about debugging.

f, err := os.Open(path)
if err != nil {
    return fmt.Errorf("failed to open file %q: %w", path, err)
}
defer f.Close()

Then, use sentinel errors or custom error types for business rules. A sentinel error is a package-level variable that callers can check with errors.Is. A custom type is a struct with an Error() string method, and it can carry extra fields.

package main

import (
    "errors"
    "fmt"
)

// sentinel error for a known business case
var ErrUserNotFound = errors.New("user not found")

// custom error type with extra details
type ValidationError struct {
    Field string
}

func (v *ValidationError) Error() string {
    return "invalid field: " + v.Field
}

func createUser(name string) error {
    if name == "" {
        return &ValidationError{Field: "name"}
    }
    return nil
}

func findUser(id int) error {
    if id != 1 {
        return fmt.Errorf("findUser %d: %w", id, ErrUserNotFound)
    }
    return nil
}

func main() {
    if err := findUser(7); errors.Is(err, ErrUserNotFound) {
        fmt.Println("handled:", err)
    }

    var vErr *ValidationError
    if err := createUser(""); errors.As(err, &vErr) {
        fmt.Println("bad field:", vErr.Field)
    }
}
handled: findUser 7: user not found
bad field: name

When does a panic happen? Go raises a runtime panic in situations like these.

  • Indexing a slice, array or string out of range.
  • Dereferencing a nil pointer.
  • Integer division by zero. Floating-point division by zero does not panic, it gives +Inf or NaN.
  • Writing to a nil map.
  • Sending on a closed channel, or closing a channel twice.
  • A failed type assertion without the , ok form.

However, calling Close on a nil *os.File does not panic. It returns the error os.ErrInvalid.

PanicError
Stops the program unless recoveredReturned and handled by the caller
For bugs and impossible statesFor expected failures
Rare in normal codeThe standard Go approach

To stop a panic, call recover() inside a deferred function, as shown in the panic and recover answer above. Servers often do this in middleware, so one bad request does not crash the whole service.

Golang Questions and Answers on Goroutines and Concurrency

Concurrency is one of the main reasons people pick Go. So these Golang questions and answers cover goroutines, channels, select, mutexes, the scheduler and the common bugs you will meet in interviews and real projects.

Q52. What are goroutines?

A goroutine is a function that runs concurrently with other code. The Go runtime manages it, not the operating system. You start one by writing the go keyword before a function call.

Goroutines are very cheap. Each one starts with a small stack of a few kilobytes, and the stack grows when needed. So a program can run thousands or even millions of them. They are not “faster” than OS threads at running code, but they are much cheaper to create and to switch between.

  • Very low memory use per goroutine
  • Cheap to create and to switch
  • Many goroutines share a small number of OS threads

Here is a small program. Each goroutine writes its result into its own slot, so the output order is always the same.

package main

import (
    "fmt"
    "sync"
)

func square(n int) int {
    return n * n
}

func main() {
    numbers := []int{1, 2, 3, 4}
    results := make([]int, len(numbers)) // one slot per goroutine

    var wg sync.WaitGroup
    for i, n := range numbers {
        wg.Add(1)
        go func() {
            defer wg.Done()
            results[i] = square(n) // each goroutine writes only its own slot
        }()
    }
    wg.Wait() // wait until every goroutine has finished

    fmt.Println(results)
}
[1 4 9 16]

Since Go 1.22 each loop iteration gets its own i and n, so the closure above is safe without copying the variables.

Q53. What is a channel in Go?

A channel is a typed pipe that lets goroutines talk to each other. One goroutine sends a value into the channel, and another goroutine receives it. This follows the Go idea “share memory by communicating” instead of sharing variables and locking them.

You create a channel with make. Then you send with ch <- value and receive with value := <-ch. On an unbuffered channel the send and the receive wait for each other, so a channel also synchronises goroutines.

TypeDescriptionExample
UnbufferedA send waits until a receiver takes the valuemake(chan int)
BufferedA send waits only when the buffer is fullmake(chan int, 5)
Receive-onlyYou can only read from itvar ch <-chan int
Send-onlyYou can only write to itvar ch chan<- int

Here is a basic example.

package main

import "fmt"

func main() {
    ch := make(chan int) // unbuffered channel of int

    go func() {
        ch <- 10 // send blocks until main receives
    }()

    value := <-ch // receive waits for the send
    fmt.Println("received:", value)
}
received: 10

Channels give you safe communication, built-in synchronisation and fewer shared-memory bugs. When the sender has no more data, it can call close(ch), and receivers can then use for v := range ch to read until the channel is empty.

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

An unbuffered channel has capacity 0. Every send blocks until another goroutine receives, and a receive blocks until another goroutine sends. So it works like a direct hand-off between two goroutines.

A buffered channel has a capacity greater than 0. A send only blocks when the buffer is full, and a receive only blocks when the buffer is empty. This means it acts like a small queue.

FeatureUnbuffered channelBuffered channel
Created withmake(chan T)make(chan T, n) with n > 0
Capacity0n
Send blocksUntil a receiver takes the valueOnly when the buffer is full
Receive blocksUntil a sender sendsOnly when the buffer is empty
BehaviourDirect hand-off, strict syncQueue, smooths out bursts
Common useSignalling and coordinationWorker pools, pipelines, rate limiting

Here is a buffered channel in action. No other goroutine is needed because the buffer holds the values.

package main

import "fmt"

func main() {
    ch := make(chan int, 3) // buffer can hold 3 values

    ch <- 1 // does not block
    ch <- 2
    ch <- 3 // buffer is now full
    fmt.Println("len:", len(ch), "cap:", cap(ch))

    fmt.Println(<-ch) // takes 1 and frees one slot
    ch <- 4           // this send succeeds right away

    fmt.Println(<-ch, <-ch, <-ch)
}
len: 3 cap: 3
1
2 3 4

If you wrote ch <- 4 while the buffer was full and nobody was receiving, the program would block forever and Go would report a deadlock.

Q55. What is the difference between concurrency and parallelism?

Concurrency means dealing with many tasks at once. The tasks can take turns on one CPU core, so their work is interleaved. Parallelism means running many tasks at exactly the same time on several CPU cores.

As Rob Pike says, concurrency is about structure, and parallelism is about execution. Goroutines give you concurrency. Then, if your machine has more than one core, the Go runtime runs goroutines in parallel.

PointConcurrencyParallelism
MeaningManaging many tasks, switching between themRunning many tasks at the same instant
GoalStructure and responsivenessSpeed
Needs many coresNoYes
AnalogyOne chef cooking many dishes by switchingSeveral chefs cooking at once
In GoGoroutines and channelsGoroutines on many cores, controlled by GOMAXPROCS

Q56. What is GOMAXPROCS?

GOMAXPROCS sets how many OS threads can run Go code at the same time. In the GMP model it is the number of P (processors). So it is the limit on how many goroutines truly run in parallel.

By default it equals the number of CPU cores the program can use. Since Go 1.25 the default also respects container CPU limits (cgroups) on Linux and updates if the limit changes. You rarely need to set it yourself. You can read or change it with the runtime package or the GOMAXPROCS environment variable.

current := runtime.GOMAXPROCS(0) // 0 means "just read the value"
fmt.Println("GOMAXPROCS:", current)

runtime.GOMAXPROCS(4) // allow at most 4 threads to run Go code at once

Threads that are blocked in system calls do not count toward this limit.

Q57. What is a mutex, and why do you use it?

A mutex (mutual exclusion lock) makes sure only one goroutine at a time runs a piece of code. That piece of code is called the critical section. Go provides it as sync.Mutex.

You need it because goroutines run concurrently. If many of them read and write the same variable without control, you get race conditions, broken data and bugs that are hard to repeat. A mutex prevents this by making the goroutines take turns.

APIPurpose
mu.Lock()Takes the lock, waits if another goroutine holds it
Release call on muGives the lock back so the next goroutine can enter
mu.TryLock()Tries to take the lock without waiting (Go 1.18+), rarely needed
sync.RWMutexA separate type that allows many readers or one writer

Here is a counter that 1000 goroutines update safely.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var (
        mu      sync.Mutex
        counter int
        wg      sync.WaitGroup
    )

    for range 1000 {
        wg.Add(1)
        go func() {
            defer wg.Done()
            mu.Lock()
            counter++ // only one goroutine runs this line at a time
            mu.Unlock()
        }()
    }
    wg.Wait()

    fmt.Println("counter:", counter)
}
counter: 1000

Without the mutex the final value could be less than 1000, because counter++ is a read, an add and a write, not one atomic step.

Q58. What is a race condition?

A race condition (a data race) happens when two or more goroutines access the same memory at the same time, and at least one of them writes. The result then depends on timing, so the program may give wrong or different results on each run. In Go, a data race is a real bug, not just a style issue.

Here is a racy counter. Two goroutines update count with no protection.

var count int

func increment(wg *sync.WaitGroup) {
    defer wg.Done()
    for range 1000 {
        count++ // not safe: read, add, write can interleave
    }
}

You can find races with the built-in race detector. Just add the -race flag.

go run -race main.go
go test -race ./...

To fix a race, protect the shared data with a sync.Mutex, use the sync/atomic package, or pass the data through a channel so only one goroutine owns it.

Q59. What is the context package used for?

The context package carries cancellation signals, deadlines and request-scoped values across function calls and goroutines. For example, when an HTTP client disconnects, the server can cancel all the work started for that request.

  • Cancellation with context.WithCancel
  • Timeouts and deadlines with context.WithTimeout and context.WithDeadline
  • Request-scoped values with context.WithValue (for things like a request ID, not for normal parameters)

Always call the cancel function, usually with defer, so resources are freed. Here is a timeout example.

package main

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

// slowWork pretends to do work that takes 2 seconds.
func slowWork(ctx context.Context) error {
    select {
    case <-time.After(2 * time.Second):
        return nil
    case <-ctx.Done(): // the context was cancelled or timed out
        return ctx.Err()
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
    defer cancel() // always release the context

    err := slowWork(ctx)
    fmt.Println("result:", err)
}
result: context deadline exceeded

By convention, ctx context.Context is the first parameter of a function.

Q60. What is the select statement?

select lets a goroutine wait on several channel operations at once. The syntax looks like switch, but each case is a send or a receive on a channel. It blocks until one of the cases can go ahead, and then it runs that case.

  • It works only with channel operations.
  • If several cases are ready, Go picks one at random, not the first one written.
  • A default case runs when no other case is ready, so the select does not block.
  • An empty select {} blocks forever.

You use select to wait on many channels, to add timeouts, to do non-blocking sends and receives, and to stop on ctx.Done(). Here is a timeout and a non-blocking receive.

package main

import (
    "fmt"
    "time"
)

func main() {
    results := make(chan string) // nobody ever sends here

    // 1. Timeout: wait for a result, but give up after 100 ms.
    select {
    case msg := <-results:
        fmt.Println("got:", msg)
    case <-time.After(100 * time.Millisecond):
        fmt.Println("timeout")
    }

    // 2. Non-blocking receive with default.
    select {
    case msg := <-results:
        fmt.Println("got:", msg)
    default:
        fmt.Println("no message ready")
    }
}
timeout
no message ready

Q61. What is the difference between a process and a thread?

A process is a running program with its own memory space. A thread is a path of execution inside a process, and all threads in a process share the same memory. So threads are lighter than processes, and switching between them is faster.

ProcessThread
Independent program with its own memoryRuns inside a process and shares its memory
Uses more memoryUses less memory
Slower to create and to switchFaster to create and to switch
A crash usually affects only that processA crash can bring down the whole process

Goroutines are lighter still. The Go runtime runs many goroutines on a few OS threads, and switching between goroutines happens in user space, without the kernel.

Q62. How does the Go scheduler work (the GMP model)?

The operating system schedules threads, not goroutines. So Go has its own scheduler inside the runtime. It maps many goroutines onto a small number of OS threads, and this design is called the GMP model.

  • G (goroutine): your function, plus its stack and its state (runnable, running or waiting). It starts with a small stack of a few kilobytes that grows when needed.
  • M (machine): a real OS thread. It runs Go code, one goroutine at a time.
  • P (processor): a scheduling context with a local run queue of goroutines. An M must hold a P to run Go code. The number of Ps equals GOMAXPROCS.

Here is how it works step by step.

  1. You create a goroutine with go f(), and the runtime puts the new G in the current P’s local run queue.
  2. An M that holds a P takes a G from that queue and runs it.
  3. When the G blocks on a channel, a lock or a sleep, the scheduler parks it and runs the next G on the same M.
  4. When a G makes a blocking system call, the P is handed to another M, so other goroutines keep running.
  5. If a P’s queue is empty, it steals work from another P’s queue or takes it from the global run queue.
  6. Long-running goroutines are preempted (since Go 1.14, even tight loops), so one goroutine cannot block the others.

The benefits are cheap scheduling of huge numbers of goroutines, low memory use, good CPU use through work stealing, and blocking calls that do not stall the whole program.

Q63. What is a channel deadlock?

A channel deadlock happens when goroutines wait on channels forever and nothing can ever wake them. If every goroutine in the program is blocked, the Go runtime stops the program with a fatal error.

The classic case is sending on an unbuffered channel when no other goroutine will receive.

package main

func main() {
    ch := make(chan int)
    ch <- 1 // blocks forever: nobody receives
}
fatal error: all goroutines are asleep - deadlock!

You can fix it by receiving in another goroutine, by using a buffered channel with enough space, or by closing channels so range loops can end. However, the runtime only detects the case where all goroutines are stuck. If some goroutines are still running, a partial deadlock just hangs quietly.

Q64. What is sync.WaitGroup?

A sync.WaitGroup waits for a group of goroutines to finish. The classic way is to call Add(1) before starting each goroutine, call Done() when it finishes, and call Wait() to block until the counter reaches zero.

package main

import (
    "fmt"
    "sync"
)

func main() {
    names := []string{"alpha", "beta", "gamma"}
    lengths := make([]int, len(names)) // fixed slots keep output in order

    var wg sync.WaitGroup
    for i, name := range names {
        wg.Add(1) // add before starting the goroutine
        go func() {
            defer wg.Done() // tell the WaitGroup this goroutine is done
            lengths[i] = len(name)
        }()
    }
    wg.Wait() // block until all three goroutines call Done

    for i, name := range names {
        fmt.Println(name, lengths[i])
    }
}
alpha 5
beta 4
gamma 5

Since Go 1.25 there is also a Go method. It calls Add and Done for you, so you cannot forget them.

package main

import (
    "fmt"
    "sync"
)

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

    for i := range 3 {
        wg.Go(func() { // Add(1), go, and Done in one call (Go 1.25+)
            results[i] = i * 10
        })
    }
    wg.Wait()

    fmt.Println(results) // [0 10 20]
}

Never copy a WaitGroup after you start using it. If you pass it to a function, pass a pointer.

Q65. What are worker pools in Go?

A worker pool is a pattern where a fixed number of goroutines (workers) take jobs from a shared channel. So you limit how many tasks run at once, instead of starting one goroutine per job. It is common in APIs, job processing and background tasks.

Here is a pool of 3 workers handling 6 jobs. Results go into a slice indexed by job number, so the output is always in order.

package main

import (
    "fmt"
    "sync"
)

func worker(jobs <-chan int, results []int, wg *sync.WaitGroup) {
    defer wg.Done()
    for job := range jobs { // loop ends when the jobs channel is closed
        results[job] = job * job
    }
}

func main() {
    const numJobs = 6
    const numWorkers = 3

    jobs := make(chan int, numJobs)
    results := make([]int, numJobs)

    var wg sync.WaitGroup
    for range numWorkers {
        wg.Add(1)
        go worker(jobs, results, &wg)
    }

    for j := range numJobs {
        jobs <- j
    }
    close(jobs) // no more jobs, workers can stop

    wg.Wait()
    fmt.Println("results:", results)
}
results: [0 1 4 9 16 25]

Q66. What is the difference between a timer and a ticker in Go?

Both come from the time package and both deliver times on a channel C. However, a time.Timer fires only once after a duration, and a time.Ticker fires again and again at a fixed interval.

Featuretime.Timertime.Ticker
FiresOnce, after the durationRepeatedly, every interval
Channeltimer.Cticker.C
Use caseTimeouts, delaysPolling, periodic jobs
Stoptimer.Stop()ticker.Stop()
Reusetimer.Reset(d)ticker.Reset(d)

Since Go 1.23, timers and tickers that you no longer reference are cleaned up by the garbage collector even if you never call Stop. Also, Reset and Stop no longer leave stale values in the channel. Still, calling defer ticker.Stop() is good practice.

package main

import (
    "fmt"
    "time"
)

func main() {
    // Timer: fires once.
    timer := time.NewTimer(30 * time.Millisecond)
    <-timer.C
    fmt.Println("timer fired once")

    // Ticker: fires every 10 ms until we stop it.
    ticker := time.NewTicker(10 * time.Millisecond)
    defer ticker.Stop()

    for i := 1; i <= 3; i++ {
        <-ticker.C
        fmt.Println("tick", i)
    }
}
timer fired once
tick 1
tick 2
tick 3

Q67. What is the difference between select and switch in Go?

switch picks a branch by comparing values or checking conditions. It never waits. select picks a branch based on which channel operation is ready, and it waits if none is ready (unless it has a default case).

Featureswitchselect
Used forMatching values or conditionsWaiting on channel operations
Cases areExpressionsChannel sends or receives
BlocksNeverYes, until a case is ready (or runs default)
Many matchesFirst matching case winsRandom choice among ready cases
Use caseNormal control flowConcurrency and goroutine coordination
package main

import "fmt"

func main() {
    // switch: compares values
    x := 2
    switch x {
    case 1:
        fmt.Println("one")
    case 2:
        fmt.Println("two")
    default:
        fmt.Println("other")
    }

    // select: waits for a ready channel
    ch1 := make(chan string, 1)
    ch2 := make(chan string, 1)
    ch1 <- "from ch1" // only ch1 has a value

    select {
    case msg := <-ch1:
        fmt.Println("received:", msg)
    case msg := <-ch2:
        fmt.Println("received:", msg)
    }
}
two
received: from ch1

Q68. Why do you lock a mutex and then release it?

Go programs are concurrent, so many goroutines may read and write the same variables at once. Without synchronisation this causes race conditions, broken data and unpredictable bugs. Lock() and the matching release call make sure only one goroutine at a time is inside the critical section.

  • mu.Lock() takes the mutex. If another goroutine holds it, the caller waits.
  • The release call gives the mutex back, so one waiting goroutine can continue.

The safest habit is to release with defer right after locking. Then the lock is freed even if the function returns early or panics.

package main

import (
    "fmt"
    "sync"
)

type Counter struct {
    mu    sync.Mutex
    count int
}

func (c *Counter) Increment() {
    c.mu.Lock()         // take the lock
    defer c.mu.Unlock() // always release it, even on early return
    c.count++           // critical section
}

func main() {
    var c Counter
    var wg sync.WaitGroup

    for range 2 {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for range 1000 {
                c.Increment()
            }
        }()
    }
    wg.Wait()

    fmt.Println("count:", c.count)
}
count: 2000
RuleWhy it matters
Always release after every Lock()Otherwise other goroutines wait forever
Release with deferIt still runs on early return or panic
Keep the locked section smallLess waiting, better performance
Do not copy a struct that holds a mutexThe copy has its own lock and protects nothing

You use this pattern for shared counters, maps and slices written by many goroutines, shared caches, and any other state touched by more than one goroutine.

Q69. If I create two receiver channels for different goroutines, will it work?

Yes. Each channel is independent, so two goroutines reading from two different channels do not interfere with each other.

There are three cases to keep in mind.

  • Separate channels: each goroutine reads its own channel and gets only its own messages.
  • One channel, many receivers: Go hands each message to exactly one receiver. So the work is shared out, like load balancing.
  • Same data for every receiver: a channel does not copy a message to all readers. Instead, you fan out by sending a copy to each receiver’s channel, or you use a pub/sub design.

Here is the second case. Two workers read from one channel, and every job is handled exactly once.

package main

import (
    "fmt"
    "sync"
)

func main() {
    jobs := make(chan int)
    handled := make([]int, 2) // how many jobs each worker handled

    var wg sync.WaitGroup
    for w := range 2 {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for range jobs {
                handled[w]++ // each worker counts only into its own slot
            }
        }()
    }

    for j := 1; j <= 10; j++ {
        jobs <- j // each value goes to only one worker
    }
    close(jobs)
    wg.Wait()

    fmt.Println("total jobs handled:", handled[0]+handled[1])
}
total jobs handled: 10

The split between the two workers can change from run to run, but the total is always 10.

Q70. How do you limit the number of goroutines in a project?

Goroutines are cheap, but starting an unlimited number can still use too much memory, CPU, open files or database connections. So you put a limit on how many run at once. There are three common ways.

  1. A buffered channel used as a semaphore. Good for small projects and simple APIs.
  2. A worker pool with a fixed number of workers. Good for batch jobs and pipelines.
  3. errgroup.Group with SetLimit. Good when you also need error handling and cancellation.

Here is the semaphore approach. The channel has 3 slots, so at most 3 tasks run at the same time.

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    const maxRunning = 3
    sem := make(chan struct{}, maxRunning) // 3 free slots

    results := make([]string, 8)
    var wg sync.WaitGroup

    for i := range results {
        wg.Add(1)
        go func() {
            defer wg.Done()
            sem <- struct{}{}        // take a slot, wait if all 3 are busy
            defer func() { <-sem }() // give the slot back

            time.Sleep(10 * time.Millisecond) // pretend to work
            results[i] = fmt.Sprintf("task %d done", i)
        }()
    }
    wg.Wait()

    for _, r := range results {
        fmt.Println(r)
    }
}
task 0 done
task 1 done
task 2 done
task 3 done
task 4 done
task 5 done
task 6 done
task 7 done

The errgroup package lives in golang.org/x/sync, which is an external module.

import "golang.org/x/sync/errgroup"

var g errgroup.Group
g.SetLimit(3) // at most 3 goroutines at once

for _, url := range urls {
    g.Go(func() error {
        return fetch(url)
    })
}
if err := g.Wait(); err != nil { // first error, after all goroutines finish
    log.Println("failed:", err)
}

Q71. How do you call multiple goroutines from main(), each doing a separate task?

You start each task with the go keyword and use a sync.WaitGroup so main waits for all of them. If main returns early, the program exits and kills every goroutine that is still running.

Each task below has a different delay, so they would finish in a random order. Because each task writes its message into its own slot, the printed result stays in order.

package main

import (
    "fmt"
    "sync"
    "time"
)

// simulateTask pretends to do some work and returns a report.
func simulateTask(name string, delay time.Duration) string {
    for step := 1; step <= 3; step++ {
        time.Sleep(delay) // one step of work
    }
    return name + " completed 3 steps"
}

func main() {
    tasks := []struct {
        name  string
        delay time.Duration
    }{
        {"Task 1", 5 * time.Millisecond},
        {"Task 2", 3 * time.Millisecond},
        {"Task 3", 7 * time.Millisecond},
        {"Task 4", 4 * time.Millisecond},
    }
    reports := make([]string, len(tasks))

    var wg sync.WaitGroup
    for i, t := range tasks {
        wg.Add(1)
        go func() {
            defer wg.Done()
            reports[i] = simulateTask(t.name, t.delay)
        }()
    }
    wg.Wait() // wait for all four tasks

    for _, r := range reports {
        fmt.Println(r)
    }
    fmt.Println("All tasks finished. Exiting main.")
}
Task 1 completed 3 steps
Task 2 completed 3 steps
Task 3 completed 3 steps
Task 4 completed 3 steps
All tasks finished. Exiting main.

Q72. How do you achieve parallelism in Go with a parallel computation?

You split the work into independent chunks and run each chunk in its own goroutine. When the machine has several cores, the runtime runs these goroutines at the same time. You do not need to call runtime.GOMAXPROCS(runtime.NumCPU()), because that is already the default.

Here the program sums the numbers from 1 to 1,000,000 in 4 parallel chunks. Each goroutine stores its partial sum in its own slot, and then main adds the slots.

package main

import (
    "fmt"
    "sync"
)

func main() {
    const n = 1_000_000
    const parts = 4

    partial := make([]int, parts) // one slot per goroutine
    chunk := n / parts

    var wg sync.WaitGroup
    for p := range parts {
        wg.Add(1)
        go func() {
            defer wg.Done()
            start := p*chunk + 1
            end := start + chunk - 1
            sum := 0
            for i := start; i <= end; i++ {
                sum += i
            }
            partial[p] = sum
        }()
    }
    wg.Wait()

    total := 0
    for p, s := range partial {
        fmt.Printf("part %d: %d\n", p, s)
        total += s
    }
    fmt.Println("total:", total)
}
part 0: 31250125000
part 1: 93750125000
part 2: 156250125000
part 3: 218750125000
total: 500000500000
FeatureUse
go func()Runs a goroutine concurrently
runtime.NumCPU()Number of CPU cores the process can use
GOMAXPROCSHow many goroutines can run in parallel (defaults to the core count)
sync.WaitGroupWaits for goroutines to finish

Parallelism only helps with CPU-heavy work that splits into independent parts. For tiny tasks, the cost of starting goroutines can be more than the time you save.

Q73. Where have you used a mutex in Go?

You use a mutex whenever several goroutines share data in memory. In real projects the common places are an in-memory cache, request counters and metrics, a shared job queue, a session or OTP store, and a rate limiter.

The most common case is a cache. A sync.RWMutex fits well here, because many goroutines read and only a few write.

package main

import (
    "fmt"
    "sync"
)

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

func NewCache() *Cache {
    return &Cache{data: make(map[string]string)}
}

// Get takes a read lock, so many readers can run together.
func (c *Cache) Get(key string) (string, bool) {
    c.mu.RLock()
    defer c.mu.RUnlock()
    val, ok := c.data[key]
    return val, ok
}

// Set takes a write lock, so it runs alone.
func (c *Cache) Set(key, value string) {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.data[key] = value
}

func main() {
    cache := NewCache()

    var wg sync.WaitGroup
    for i := range 5 {
        wg.Add(1)
        go func() {
            defer wg.Done()
            cache.Set(fmt.Sprintf("user%d", i), fmt.Sprintf("token%d", i))
        }()
    }
    wg.Wait()

    for i := range 5 {
        val, _ := cache.Get(fmt.Sprintf("user%d", i))
        fmt.Println(val)
    }
}
token0
token1
token2
token3
token4

For one-time setup, such as opening a database connection, use sync.Once instead of a mutex. It runs the setup function exactly once, even when many goroutines call it.

You do not need a mutex if only one goroutine touches the data, if a channel already hands the data from owner to owner, or if the database handles the locking for you. A simple rule of thumb is “use a mutex for state, use channels for flow”.

MutexChannel
Protects shared memoryPasses data between goroutines (share by communicating)
Best for guarding stateBest for workflows and pipelines
Very low overheadA bit more overhead, but clearer for hand-offs

Q74. How do you write an async function in Go?

Go has no async and await keywords. Instead, you run a function in a goroutine with the go keyword, and the caller keeps going without waiting. To get the result back, you usually return a channel, or you use a sync.WaitGroup, an errgroup or a context.

Here is a simple “future” style function that returns a channel.

package main

import (
    "fmt"
    "time"
)

// fetchPrice starts the work in a goroutine and returns at once.
func fetchPrice(item string) <-chan int {
    result := make(chan int, 1) // buffered so the goroutine never gets stuck
    go func() {
        time.Sleep(20 * time.Millisecond) // pretend this is a slow API call
        result <- len(item) * 100
    }()
    return result
}

func main() {
    applePrice := fetchPrice("apple") // both calls start right away
    kiwiPrice := fetchPrice("kiwi")

    fmt.Println("doing other work...")

    // Now wait for the results.
    fmt.Println("apple:", <-applePrice)
    fmt.Println("kiwi:", <-kiwiPrice)
}
doing other work...
apple: 500
kiwi: 400

When you run code this way, watch for three common problems.

  • Race conditions: several goroutines touch shared memory. So protect it with a mutex or use channels.
  • Goroutine leaks: goroutines that never stop keep using memory. Stop them with a context or by closing channels.
  • Deadlocks: goroutines that wait on each other forever. Plan who sends, who receives and who closes.

This style works well for API calls, file processing, background jobs, microservices and parallel computation.

Q75. How do you detect a race condition in your code?

The best tool is the Go race detector. You turn it on with the -race flag when you run, test or build your program.

go run -race main.go
go test -race ./...
go build -race -o app .

When the detector sees two goroutines touching the same memory without synchronisation, it prints a “WARNING: DATA RACE” report. The report shows both stack traces, so you can find the exact lines. However, it only finds races in code paths that actually run, so good tests matter. Also, it makes programs slower, so use it in tests and CI rather than in production.

Even without the detector, some signs point to a race.

  • Output that changes from run to run
  • Values that are wrong or impossible
  • Random crashes, such as “concurrent map writes”

Q76. What is a goroutine leak?

A goroutine leak happens when a goroutine keeps running or stays blocked after you no longer need it. It never exits, so its stack and the memory it points to are never freed. Over time, leaks make memory use grow until the service slows down or crashes.

Common causes are a goroutine blocked on a channel that nobody will send to or receive from, a loop with no exit condition, and work that ignores cancellation. You can fix them in these ways.

  • Pass a context and stop when ctx.Done() is closed (for example with context.WithCancel).
  • Close channels when there is no more data, so range loops end.
  • Give every loop a clear exit path.
package main

import (
    "context"
    "fmt"
    "sync"
)

func worker(ctx context.Context, jobs <-chan int, wg *sync.WaitGroup) {
    defer wg.Done()
    for {
        select {
        case <-ctx.Done(): // stop when the caller cancels
            fmt.Println("worker stopped:", ctx.Err())
            return
        case j := <-jobs:
            fmt.Println("processed job", j)
        }
    }
}

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    jobs := make(chan int)

    var wg sync.WaitGroup
    wg.Add(1)
    go worker(ctx, jobs, &wg)

    jobs <- 1
    jobs <- 2

    cancel()  // without this, the worker would wait on jobs forever
    wg.Wait() // make sure it really exited
}
processed job 1
processed job 2
worker stopped: context canceled

Q77. What is context switching?

Context switching is when the CPU stops running one process or thread and starts running another. First the system saves the state of the current task, such as its registers and program counter. Then it loads the saved state of the next task.

A switch between OS threads goes through the kernel, so it is fairly costly. Goroutine switches are much cheaper, because the Go scheduler does them in user space and saves only a few registers. This is one reason Go can run so many goroutines.

Q78. What happens if you forget to release a mutex lock?

Every other goroutine that calls Lock() on that mutex waits forever. If all goroutines end up stuck this way, the runtime stops with “all goroutines are asleep – deadlock!”. If only some are stuck, your program just hangs or stops responding.

The fix is to release the lock with defer straight after taking it.

mu.Lock()
defer mu.Unlock() // runs on every return path, even on panic

// critical section

Q79. What is the difference between Mutex and RWMutex?

sync.Mutex lets only one goroutine hold the lock, whether it reads or writes. sync.RWMutex lets many readers hold a read lock at the same time, but a writer gets the lock alone.

sync.Mutexsync.RWMutex
One goroutine at a time, for reads and writesMany readers at once, or one writer
Simpler and slightly faster per callBetter for read-heavy workloads
Methods: Lock() and its release methodRLock() / RUnlock() for reads, plus the write lock pair

Use RWMutex only when reads are much more common than writes, for example a cache or a config store. Otherwise, a plain Mutex is simpler and often just as fast.

Q80. What is a deadlock?

A deadlock is when two or more goroutines are blocked forever, each waiting for something that will never happen. So the program cannot make progress. If every goroutine is blocked, Go stops the program with a fatal error.

The simplest example is a send on an unbuffered channel with no receiver.

package main

func main() {
    ch := make(chan int)
    ch <- 10 // blocks forever
}
fatal error: all goroutines are asleep - deadlock!

This happens because an unbuffered channel needs a receiver. No goroutine is receiving, so the send waits forever. Other common causes are two goroutines that take two mutexes in opposite order, and a wg.Wait() whose matching Done() calls never come.

Q81. Does GMP increase or decrease the number of threads?

Neither, really. The goal of GMP is to run a large number of goroutines on a small number of OS threads. So the runtime keeps threads few and changes their number only when it needs to.

  • It adds threads when needed. For example, when a thread blocks in a system call (like file I/O), the runtime hands its P to another thread so other goroutines keep running.
  • It reuses threads. When the blocked thread is free again, it goes back to a pool of idle threads instead of being thrown away.
  • At most GOMAXPROCS threads run Go code at once. Extra threads exist only for blocked system calls.

In an interview you can say this. “GMP does not just add or remove threads. It schedules many goroutines onto a few OS threads, creates extra threads only when one blocks, and reuses threads whenever it can.”

Q82. Which channel is synchronous in Go?

An unbuffered channel is synchronous. The sender and the receiver must meet at the same moment. So a send blocks until another goroutine receives, and a receive blocks until another goroutine sends.

A buffered channel is asynchronous up to its capacity. A send goes ahead without a receiver as long as the buffer has space. Once the buffer is full, sends block until a receiver takes a value.

package main

import "fmt"

func main() {
    buffered := make(chan string, 1)
    buffered <- "hello" // works with no receiver, because there is space
    fmt.Println("buffered send done")
    fmt.Println(<-buffered)

    unbuffered := make(chan string)
    go func() {
        unbuffered <- "hi" // waits here until main receives
    }()
    fmt.Println(<-unbuffered) // the hand-off happens here
}
buffered send done
hello
hi

Q83. What does synchronous mean?

Synchronous means one operation waits for another to finish before it continues. For example, a normal function call is synchronous, because the caller waits for the function to return.

In Go, an unbuffered channel is synchronous. The sender blocks until a receiver is ready, and the receiver blocks until a sender provides a value. So both goroutines meet at the point of communication. The opposite is asynchronous, where the caller starts the work and carries on without waiting, like starting a goroutine with go.

Golang Questions and Answers on Memory, GC and Performance

These Golang questions and answers cover how Go manages memory, how the garbage collector works and how you keep a Go service fast. You will also see how to find and fix memory leaks, CPU spikes and slow responses.

Q84. What is garbage collection in Go?

Garbage collection (GC) is automatic memory management. Go finds memory that your program can no longer reach and frees it for you. So you never call free like you do in C or C++.

Go uses a concurrent, tri-colour mark and sweep collector. It runs mostly in the background, at the same time as your goroutines. Because of this, the “stop the world” pauses are very short, usually well under a millisecond.

Here is why garbage collection helps you.

  • It removes most manual memory bugs, such as double free and use after free.
  • It lowers the risk of memory leaks, but it cannot remove all of them.
  • You write less code, so you get more done.

You can tune the collector with two settings. GOGC (default 100) controls how much the heap may grow before the next cycle. GOMEMLIMIT sets a soft memory limit, which is useful in containers.

Q85. What is mark and sweep in Go’s garbage collector?

Mark and sweep is the method Go’s GC uses to find and free unused memory. It works in two phases.

  • Mark phase. The GC starts from the roots (globals, stacks and registers) and follows every pointer. Each object it can reach is marked as live.
  • Sweep phase. The GC walks the heap and frees every object that was not marked. That memory goes back to Go’s allocator for reuse.

Think of it like cleaning your desk. First, you tag the papers you still need. Then you throw away everything without a tag.

The “tri-colour” part describes how marking is tracked. White objects are not yet seen, grey objects are seen but their pointers are not yet scanned, and black objects are fully scanned. When no grey objects remain, every white object is garbage. A write barrier keeps this correct while your code changes pointers during marking.

Go’s collector does not compact memory, so it never moves objects around. Since Go 1.26, the default collector also uses the “Green Tea” design. It scans memory in small pages for better CPU cache use, but the idea is still mark and sweep.

People sometimes mix this up with make. However, make is not part of the GC. It is a built-in function that allocates and sets up slices, maps and channels so they are ready to use. When nothing refers to that slice, map or channel any more, the GC frees it in a later cycle.

package main

import "fmt"

func main() {
    // make allocates and initialises a slice, a map and a channel.
    scores := make([]int, 3)
    ages := make(map[string]int)
    jobs := make(chan string, 2)

    ages["Asha"] = 30
    jobs <- "build"

    fmt.Println(len(scores), len(ages), len(jobs))

    // new only allocates zeroed memory and returns a pointer.
    count := new(int)
    fmt.Println(*count)

    // After this, nothing refers to the old slice, so the GC can free it.
    scores = nil
    fmt.Println(scores == nil)
}
3 1 1
0
true

Q86. How do you avoid memory leaks in Go?

Most leaks in Go come from things that stay referenced or never stop. So the fix is to give every resource and every goroutine a clear end.

  • Stop goroutines. A goroutine that waits forever on a channel leaks. Give it a way to stop, such as context.Context or a done channel.
  • Close channels when the sender is finished, so receivers can exit their range loops.
  • Drop references you no longer need. For example, set a large global value to nil or remove old keys from a map.
  • Close files, database rows, HTTP response bodies and network connections. Use defer right after you open them.
  • Watch your service with pprof and the goroutine count, so you spot growth early.

Here is a worker that stops cleanly when its context is cancelled.

package main

import (
    "context"
    "fmt"
)

func worker(ctx context.Context, jobs <-chan int, done chan<- string) {
    for {
        select {
        case <-ctx.Done():
            // Context cancelled, so the goroutine exits and frees its memory.
            done <- "worker stopped"
            return
        case job := <-jobs:
            fmt.Println("processed job", job)
        }
    }
}

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    jobs := make(chan int)
    done := make(chan string)

    go worker(ctx, jobs, done)

    jobs <- 1
    jobs <- 2

    cancel() // tell the worker to stop
    fmt.Println(<-done)
}
processed job 1
processed job 2
worker stopped

Q87. How do you reduce GC overhead in Go?

The GC has more work when you allocate a lot and when the heap holds many pointers. So you reduce overhead by allocating less and keeping data simple.

  • Reuse objects with sync.Pool, for example buffers in a busy HTTP handler.
  • Preallocate slices and maps when you know the size, such as make([]int, 0, 1000).
  • Avoid needless pointers. A slice of structs is cheaper to scan than a slice of pointers to structs.
  • Avoid building strings in a loop with +. Use strings.Builder instead.
  • Tune GOGC and GOMEMLIMIT if profiling shows the GC uses too much CPU.

Here is a small example that reuses buffers with sync.Pool.

package main

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

// bufferPool hands out reusable buffers instead of allocating new ones.
var bufferPool = sync.Pool{
    New: func() any {
        return new(bytes.Buffer)
    },
}

func greet(name string) string {
    buf := bufferPool.Get().(*bytes.Buffer)
    buf.Reset() // clear old data before use
    defer bufferPool.Put(buf)

    buf.WriteString("Hello, ")
    buf.WriteString(name)
    return buf.String()
}

func main() {
    fmt.Println(greet("Go"))
    fmt.Println(greet("Gopher"))
}
Hello, Go
Hello, Gopher

Q88. Does the garbage collector prevent memory leaks?

No, not always. The GC only frees memory that nothing refers to. If your code still holds a reference, the GC must keep that memory, even if you will never use it again.

Here are the usual causes of leaks in Go.

  • Goroutines that are stuck forever on a channel, a lock or a network call.
  • Resources you never close, such as files, response bodies or database rows.
  • Maps and caches that grow without any limit.
  • A small sub-slice that keeps a huge backing array alive.
  • Global variables that hold large data for the whole life of the program.

So you still need good habits. Close resources with defer, and control goroutines with context cancellation, timeouts and worker pools. Also, put a size limit on caches and be careful with very large channel buffers. Then check heap and goroutine profiles with pprof to confirm nothing keeps growing.

Q89. What is escape analysis in Go?

Escape analysis is a compiler step that decides where a variable lives, on the stack or on the heap. The Go compiler does this at compile time, so you do not choose it yourself.

  • Stack. Allocation is very fast, and the memory is freed when the function returns. It is used for values that do not outlive the function.
  • Heap. Allocation is slower, and the GC frees the memory later. It is used when a value must live after the function returns.

A value “escapes” to the heap when the compiler cannot prove it stays inside the function. For example, returning a pointer to a local variable makes it escape. Storing a value in an interface or a global can also make it escape.

package main

import "fmt"

type User struct {
    Name string
}

// newUser returns a pointer, so u escapes to the heap.
func newUser(name string) *User {
    u := User{Name: name}
    return &u
}

// sum keeps total on the stack because it never leaves the function.
func sum(nums []int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

func main() {
    u := newUser("Asha")
    fmt.Println(u.Name)
    fmt.Println(sum([]int{1, 2, 3}))
}
Asha
6

You can see the compiler’s decisions with the -gcflags=-m flag.

go build -gcflags=-m .
# ./main.go:11:2: moved to heap: u

Escape analysis matters because fewer heap allocations mean less GC work. As a result, your program runs faster without any manual memory code.

Q90. What is a memory leak?

A memory leak happens when a program keeps holding memory it no longer needs. That memory cannot be reused, so memory use grows over time. Finally, this can slow the service down or make it crash with an out of memory error.

In C or C++, a leak usually means you forgot to call free. In Go, the GC frees unreachable memory for you. So a Go leak usually means your program still has a reference to data it no longer needs.

Here is a common case. A small sub-slice keeps the whole large backing array alive. Copying the part you need lets the GC free the big array.

package main

import "fmt"

// firstThreeLeaky returns a sub-slice that still points at the big array.
func firstThreeLeaky(big []byte) []byte {
    return big[:3]
}

// firstThreeSafe copies the bytes, so the big array can be collected.
func firstThreeSafe(big []byte) []byte {
    small := make([]byte, 3)
    copy(small, big[:3])
    return small
}

func main() {
    big := make([]byte, 1_000_000)

    leaky := firstThreeLeaky(big)
    safe := firstThreeSafe(big)

    fmt.Println("leaky cap:", cap(leaky))
    fmt.Println("safe cap:", cap(safe))
}
leaky cap: 1000000
safe cap: 3

Here is how you prevent leaks.

  • Remove references to objects you no longer need.
  • Close files, database rows and network connections.
  • Stop goroutines with context.Context or a done channel.
  • Put limits on slices, maps and caches that grow over time.
  • Close channels when the sender is done.

To find leaks, expose net/http/pprof in your service and read the heap and goroutine profiles.

go tool pprof http://localhost:6060/debug/pprof/heap
go tool pprof http://localhost:6060/debug/pprof/goroutine

You can also read memory stats from inside your program.

var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Println("heap in use (bytes):", m.HeapAlloc)

Q91. What causes a CPU spike, and how do you handle it?

A CPU spike is a sudden jump in CPU use. In a Go service it usually comes from one of these causes.

  • A burst of traffic, so more requests run at the same time.
  • Slow code, such as nested loops, heavy JSON work or regex compiled on every request.
  • Too many goroutines doing work at once, with no limit.
  • A lot of garbage collection, because the code allocates too much.
  • Busy loops or retry storms that never wait between tries.

First, confirm the spike with system metrics, for example in Prometheus and Grafana. Next, take a CPU profile to see which functions use the most time.

go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30

Then fix the hot path. You can optimise the code, cache results, cut allocations and limit concurrency with a worker pool. Also, add rate limiting and autoscaling so traffic bursts do not overload a single instance.

Q92. How do you reduce latency in a Go service?

Latency is the time a request takes from start to finish. You reduce it by removing slow work from the request path.

  • Cache data that is read often, in memory or in Redis.
  • Reduce database calls. For example, fetch data in one query instead of many small ones.
  • Use connection pooling, which database/sql and net/http do for you.
  • Optimise queries with the right indexes, and select only the columns you need.
  • Run independent calls in parallel with goroutines, then wait for all of them.
  • Set timeouts with context so one slow dependency cannot block everything.

Always measure first with metrics or pprof. Then you fix the real bottleneck instead of guessing.

Q93. What is the difference between a memory leak and a goroutine leak?

A memory leak means data stays referenced, so the GC cannot free it. A goroutine leak means goroutines stay blocked or running forever. Also, a goroutine leak is a kind of memory leak, because each stuck goroutine keeps its stack and every value it refers to.

Memory leakGoroutine leak
Unused memory stays referenced and cannot be collectedGoroutines stay blocked or running forever
Heap usage keeps growingThe goroutine count keeps growing
Mostly affects memory and GC timeAffects memory, scheduling and CPU
Found with the heap profileFound with the goroutine profile or runtime.NumGoroutine

Here is a goroutine leak in action. Each goroutine waits on a channel that nobody ever sends to.

package main

import (
    "fmt"
    "runtime"
)

func leak() {
    ch := make(chan int)
    go func() {
        <-ch // blocks forever, because nothing sends on ch
    }()
}

func main() {
    before := runtime.NumGoroutine()
    for i := 0; i < 3; i++ {
        leak()
    }
    after := runtime.NumGoroutine()
    fmt.Println("leaked goroutines:", after-before)
}
leaked goroutines: 3

Golang Questions and Answers on Web, REST APIs and Security

These Golang questions and answers cover building web servers and REST APIs in Go, from routing and middleware to frameworks like Gin and Fiber. You will also learn the security basics, such as CORS, JWT, OAuth, authentication and authorization.

Q94. What is middleware in Go?

Middleware is a function that wraps your handler. It runs before your handler, after it, or both. So it can read or change the request and the response in one shared place.

You can use middleware with plain net/http or with frameworks like Gin, Fiber and Echo. Here are common uses.

  • Logging requests
  • Authentication and authorization
  • Request validation
  • Adding CORS headers
  • Rate limiting
  • Compressing responses
  • Recovering from panics

In net/http, middleware takes an http.Handler and returns a new http.Handler. Here is a logging middleware tested with httptest, so no real server is needed.

package main

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

// logging wraps next and prints a line before and after it runs.
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)
        fmt.Println("after:", r.URL.Path)
    })
}

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

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

    req := httptest.NewRequest(http.MethodGet, "/hello", nil)
    rec := httptest.NewRecorder()
    handler.ServeHTTP(rec, req)

    fmt.Println("response:", rec.Body.String())
}
before: GET /hello
handler running
after: /hello
response: Hello

Q95. What is CORS?

CORS stands for Cross-Origin Resource Sharing. It is a browser security rule that controls whether a web page can call a server on a different origin. An origin is the mix of protocol, domain and port, so https://app.com and https://api.app.com are different origins.

By default, browsers block these cross-origin calls from JavaScript. This protects users from harmful sites. CORS lets your server tell the browser which other origins it trusts.

Here is how it works.

  1. The browser sends the request. For some requests it first sends a “preflight” OPTIONS request.
  2. The server replies with headers such as Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers.
  3. If the headers allow it, the browser lets the page read the response.

CORS is enforced by the browser only. So it does not protect your API from tools like curl, and you still need authentication. Here is a simple CORS middleware in Go.

package main

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

const allowedOrigin = "https://myfrontend.com"

// cors adds CORS headers and answers preflight requests.
func cors(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.Header.Get("Origin") == allowedOrigin {
            w.Header().Set("Access-Control-Allow-Origin", allowedOrigin)
            w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
            w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
        }
        if r.Method == http.MethodOptions {
            w.WriteHeader(http.StatusNoContent) // preflight needs no body
            return
        }
        next.ServeHTTP(w, r)
    })
}

func main() {
    api := cors(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "data")
    }))

    req := httptest.NewRequest(http.MethodOptions, "/users", nil)
    req.Header.Set("Origin", "https://myfrontend.com")
    rec := httptest.NewRecorder()
    api.ServeHTTP(rec, req)

    fmt.Println("status:", rec.Code)
    fmt.Println("allow origin:", rec.Header().Get("Access-Control-Allow-Origin"))
    fmt.Println("allow methods:", rec.Header().Get("Access-Control-Allow-Methods"))
}
status: 204
allow origin: https://myfrontend.com
allow methods: GET, POST

In real projects you can also use a ready package such as github.com/rs/cors.

Q96. What do you use to secure a REST API in Go?

No single tool secures an API. Instead, you combine several layers.

  1. Authentication (who you are). Use JWT for stateless APIs, OAuth 2.0 or OpenID Connect for third-party login, and API keys for service-to-service calls. Basic Auth is only acceptable over HTTPS.
  2. Authorization (what you can do). Use role-based access control (RBAC), such as admin and user roles. For finer rules, use attribute-based access control (ABAC).
  3. Transport security. Always use HTTPS (TLS), so nobody can read or change data in transit.
  4. Input validation. Check the body, query, headers and path values. Use parameterised SQL queries to stop SQL injection, and escape output to stop XSS.
  5. CORS. Allow only the origins, methods and headers you need.
  6. Rate limiting. Block brute force attacks and abuse with golang.org/x/time/rate, or at a proxy like Nginx or Cloudflare.
  7. Logging and monitoring. Log failed logins and unusual activity, but never log passwords or tokens. Monitor with Prometheus and Grafana or the ELK stack.
  8. Data protection. Hash passwords with bcrypt or argon2, and encrypt sensitive data at rest.
  9. Middleware. Put auth checks, validation and panic recovery in middleware, so error pages never leak stack traces.

Here is an auth middleware in Gin. It needs the Gin module, so it does not run here.

func AuthMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        token := strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer ")
        if !validateJWT(token) {
            c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
            return
        }
        c.Next() // token is valid, so continue to the handler
    }
}

In short, use HTTPS, JWT or OAuth, RBAC, rate limiting, input validation and logging together.

Q97. How do you use OAuth with a third-party provider but allow only some users in Go?

You let the provider prove who the user is. Then your own code decides if that user may come in. Here is the flow.

  1. The user clicks “Sign in” and your app redirects them to the provider (Google, GitHub and so on) with your client ID.
  2. Next, the user logs in and grants permission.
  3. The provider redirects back to your app with a short-lived code.
  4. Your backend exchanges the code for tokens, using the client ID and client secret.
  5. You verify the ID token, or call the provider’s user info API, to get the email or user ID.
  6. You check that user against your own allowlist, in a database, a config file or a role table.
  7. If the user is allowed, you issue your own session or JWT. Otherwise, you return 403 Forbidden.

The client ID identifies your app to the provider. The client secret proves your app is genuine, so keep it on the server and never send it to the browser.

Two libraries cover most needs. golang.org/x/oauth2 handles the OAuth flow, and github.com/coreos/go-oidc/v3 verifies OpenID Connect ID tokens. Here is the code exchange step. It needs those modules, so it does not run here.

conf := &oauth2.Config{
    ClientID:     os.Getenv("OAUTH_CLIENT_ID"),
    ClientSecret: os.Getenv("OAUTH_CLIENT_SECRET"),
    RedirectURL:  "https://myapp.com/auth/callback",
    Scopes:       []string{"openid", "email"},
    Endpoint:     google.Endpoint,
}

// In the callback handler, swap the code for tokens.
token, err := conf.Exchange(r.Context(), r.URL.Query().Get("code"))

The allowlist check itself is plain Go.

package main

import (
    "fmt"
    "strings"
)

// allowed holds the emails that may use the app.
var allowed = map[string]bool{
    "asha@example.com":  true,
    "ravi@example.com":  true,
}

func isAllowed(email string) bool {
    return allowed[strings.ToLower(email)]
}

func main() {
    for _, email := range []string{"Asha@example.com", "guest@example.com"} {
        if isAllowed(email) {
            fmt.Println(email, "-> access granted")
        } else {
            fmt.Println(email, "-> 403 Forbidden")
        }
    }
}
Asha@example.com -> access granted
guest@example.com -> 403 Forbidden

Q98. Which comes first, authentication or authorization?

Authentication always comes first, then authorization. The system cannot decide what you may do until it knows who you are.

StepMeaningQuestion it answers
AuthenticationChecks who the user is“Are you really this user?”
AuthorizationChecks what the user may do“What are you allowed to do?”

Here is the order in a real flow.

  1. The user logs in with a username and password (authentication).
  2. The system confirms the identity and creates a token or session.
  3. On each request, the system checks the user’s roles and permissions (authorization).
  4. The user is allowed or denied access to the feature.

Think of an office. At the gate, security checks your ID card, which is authentication. Inside, your access card decides which floors you can enter, which is authorization.

Q99. What is a 401 API response?

HTTP 401 Unauthorized means the request lacks valid authentication. The name is confusing, because it really means “unauthenticated”. You usually get a 401 in these cases.

  • No token was sent, or the Authorization header is missing.
  • An expired token was sent.
  • The token is invalid or malformed.
  • The username or password is wrong.

A 401 response often looks like this.

{
  "error": "unauthorized",
  "message": "invalid or missing token"
}

People often mix up 401 and 403.

StatusMeaningCause
401 UnauthorizedAuthentication failedThe user is not logged in or the token is invalid
403 ForbiddenAuthorization failedThe user is logged in but lacks permission

Here is how you fix a 401.

ProblemSolution
Token not sentAdd Authorization: Bearer <token> to the header
Token expiredUse a refresh token or log in again
Invalid tokenGet a new token
Wrong credentialsCorrect the username or password

This Go handler returns 401 or 403 depending on the case.

package main

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

// tokens maps a token to its user role. A real app would verify a JWT.
var tokens = map[string]string{"admin-token": "admin", "user-token": "user"}

func adminOnly(w http.ResponseWriter, r *http.Request) {
    role, ok := tokens[r.Header.Get("Authorization")]
    if !ok {
        http.Error(w, "unauthorized", http.StatusUnauthorized) // who are you?
        return
    }
    if role != "admin" {
        http.Error(w, "forbidden", http.StatusForbidden) // you may not do this
        return
    }
    fmt.Fprint(w, "welcome, admin")
}

func main() {
    for _, token := range []string{"", "user-token", "admin-token"} {
        req := httptest.NewRequest(http.MethodGet, "/admin", nil)
        req.Header.Set("Authorization", token)
        rec := httptest.NewRecorder()
        adminOnly(rec, req)
        fmt.Printf("token=%q status=%d\n", token, rec.Code)
    }
}
token="" status=401
token="user-token" status=403
token="admin-token" status=200

Q100. What is authorization?

Authorization decides what an authenticated user is allowed to access or do. It always happens after authentication.

For example, a user first logs in with a username and password. Then the system checks questions like these.

  • Can this user open the dashboard?
  • Is this user allowed to delete a record?
  • Can this user upload a file?

In Go, you usually check roles or permissions in middleware before the handler runs. If the check fails, you return 403 Forbidden.

Q101. What is Gorilla Mux, and how does routing work in Gin?

Gorilla Mux and Gin are separate routers. You do not use Gorilla Mux inside Gin. You pick one of them for a project.

LibraryPackageWhat it is
Gorilla Muxgithub.com/gorilla/muxA router that plugs into net/http
Gingithub.com/gin-gonic/ginA full web framework with its own router

Gorilla Mux gives net/http extra routing features. These include path variables like /users/{id}, method matching, query and header matching, and middleware. The project was archived in 2022 but is maintained again since 2023.

Here is routing with Gorilla Mux. It needs the module, so it does not run here.

package main

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

    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
        id := mux.Vars(r)["id"] // read the path variable
        fmt.Fprintf(w, "User ID: %s", id)
    }).Methods(http.MethodGet)

    log.Fatal(http.ListenAndServe(":8080", r))
}

Gin has its own router, built on a fast radix tree. You register a route with a method function like r.GET, and path parameters use a colon, such as /users/:id.

package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/users/:id", func(c *gin.Context) {
        c.JSON(200, gin.H{"user_id": c.Param("id")})
    })
    r.Run(":8080")
}

Since Go 1.22, the standard net/http mux also supports methods and path variables, such as "GET /users/{id}". So for many small APIs you need neither library.

Q102. What is Gin used for?

Gin is a fast web framework for Go. It gives you a router, middleware, JSON handling, request binding and validation in one package. It is built on top of net/http, so it works with standard Go handlers and tools.

package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default() // includes logger and panic recovery middleware

    r.GET("/users/:id", func(c *gin.Context) {
        id := c.Param("id")
        c.JSON(200, gin.H{"user_id": id})
    })

    r.Run(":8080")
}

Here is how its routing style compares with Gorilla Mux.

FeatureGorilla MuxGin
Path parameter{id}:id
ResponseManual, with fmt.Fprintf or json.NewEncoderHelpers like c.JSON and c.String
SpeedFast enough for most appsVery fast router
ScopeRouter onlyRouter, middleware, binding and validation
Learning curveSimpleModerate
Use Gorilla Mux whenUse Gin when
You want a simple routerYou want a full web backend
You prefer plain net/httpYou need fast JSON APIs
The project is smallYou build a larger REST API

Q103. What is the difference between query parameters and path parameters?

Path parameters are part of the route itself, such as 10 in /users/10. They identify one specific resource, so they are required. Query parameters come after the ?, such as /users?role=admin&page=2. They are optional and are used for filters, search, sorting and pagination.

FeatureQuery parametersPath parameters
Place in URLAfter ?Inside the route
RequiredNoYes
PurposeFilters, search, optional inputsIdentify a specific resource
Example/users?role=admin/users/10
Read in Ginc.Query("role")c.Param("id")
Read in net/httpr.URL.Query().Get("role")r.PathValue("id")

Here is both kinds read with the standard library.

package main

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

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
        id := r.PathValue("id")               // path parameter
        fields := r.URL.Query().Get("fields") // query parameter
        fmt.Fprintf(w, "id=%s fields=%s", id, fields)
    })

    req := httptest.NewRequest(http.MethodGet, "/users/10?fields=name", nil)
    rec := httptest.NewRecorder()
    mux.ServeHTTP(rec, req)
    fmt.Println(rec.Body.String())
}
id=10 fields=name

Q104. How do you manage a cache in Go?

For a single service instance, an in-memory cache is the simplest choice. It gives very fast reads, but the data is lost on restart. When you run many instances, use a shared cache like Redis so all of them see the same data.

Here is a small, safe in-memory cache. A sync.RWMutex lets many readers in at once, but only one writer.

package main

import (
    "fmt"
    "sync"
)

// Cache is a map protected by a read-write mutex.
type Cache struct {
    mu    sync.RWMutex
    items map[string]string
}

func NewCache() *Cache {
    return &Cache{items: make(map[string]string)}
}

func (c *Cache) Get(key string) (string, bool) {
    c.mu.RLock()
    defer c.mu.RUnlock()
    value, ok := c.items[key]
    return value, ok
}

func (c *Cache) Set(key, value string) {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.items[key] = value
}

func main() {
    cache := NewCache()
    cache.Set("user:1", "Asha")

    if name, ok := cache.Get("user:1"); ok {
        fmt.Println("hit:", name)
    }
    if _, ok := cache.Get("user:2"); !ok {
        fmt.Println("miss: load from database")
    }
}
hit: Asha
miss: load from database

Here are some good caching rules.

  • Cache data that is read often and changes rarely.
  • Set an expiry time (TTL) and a size limit, so the cache cannot grow forever.
  • Never cache auth-sensitive data blindly, because a user could see another user’s data.
  • Measure the hit ratio to check the cache really helps.

Q105. How do you do authentication and authorization in Go?

Authentication answers “Who are you?”, for example with a login and a token. Authorization answers “What are you allowed to do?”, for example with roles and permissions. Authentication always comes first.

There are four common ways to authenticate in Go.

  1. Basic Auth, with a username and password in a header. It is simple, but rarely used in production.
  2. Sessions, with a session ID in a cookie. This is typical for server-rendered web apps.
  3. Tokens, such as JWT. This is the most common choice for APIs.
  4. Third-party login with OAuth 2.0 and OpenID Connect, for example Google or GitHub.

A JWT flow works like this. The user logs in, you verify the password with bcrypt and you create a signed JWT. Then the client sends the JWT on every request, and middleware validates it.

Here is how you create and check a token with github.com/golang-jwt/jwt/v5. It needs that module, so it does not run here.

var secret = []byte(os.Getenv("JWT_SECRET"))

// createToken signs a short-lived token with the user's ID and role.
func createToken(userID, role string) (string, error) {
    claims := jwt.MapClaims{
        "sub":  userID,
        "role": role,
        "exp":  time.Now().Add(15 * time.Minute).Unix(),
    }
    return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret)
}

// parseToken checks the signature, the algorithm and the expiry.
func parseToken(tokenString string) (jwt.MapClaims, error) {
    token, err := jwt.Parse(tokenString, func(t *jwt.Token) (any, error) {
        return secret, nil
    }, jwt.WithValidMethods([]string{"HS256"}))
    if err != nil {
        return nil, err
    }
    return token.Claims.(jwt.MapClaims), nil
}

Then a second middleware checks the role from the claims, which is authorization. It returns 403 if the role is not allowed.

ScenarioCommon solution
Simple APIJWT
MicroservicesJWT, with Redis for revoked tokens
EnterpriseOAuth 2.0 or OpenID Connect with Keycloak
Mobile appShort-lived JWT with a refresh token

In short, authenticate with a login and JWT, then authorize with role middleware. Also protect routes with middleware, hash passwords with bcrypt and always use HTTPS.

Q106. What is the difference between Fiber and Gin?

Both are popular Go web frameworks, but they sit on different HTTP engines. Fiber is built on fasthttp, while Gin is built on the standard net/http.

FeatureFiberGin
HTTP enginefasthttpnet/http
Raw speedVery high in benchmarksHigh
Memory useLowLow
StyleSimilar to Express.jsStandard Go style
Works with net/http middlewareOnly through adaptersYes
HTTP/2Not supported by fasthttpSupported

Choose Fiber when you want top raw speed for small microservices or you like Express.js syntax. Choose Gin when you want standard Go behaviour, wide library support and a long production record.

In real systems, the framework is rarely the bottleneck. Database queries, caching and architecture matter much more than benchmark numbers.

Q107. Which command installs Fiber in Go?

Fiber v3 is the current major version, so you install it with this command.

go get github.com/gofiber/fiber/v3

Fiber v3 needs a recent Go version, so check its README for the minimum. Older projects still use v2, which you install with go get github.com/gofiber/fiber/v2. The import path must match the version you installed.

Here is a small Fiber v3 app. In v3 the handler takes fiber.Ctx (an interface), not *fiber.Ctx like in v2.

package main

import (
    "log"

    "github.com/gofiber/fiber/v3"
)

func main() {
    app := fiber.New()

    app.Get("/", func(c fiber.Ctx) error {
        return c.SendString("Hello, Fiber")
    })

    log.Fatal(app.Listen(":3000"))
}

Q108. What are the parts of a JWT?

A JWT has three parts joined by dots, header.payload.signature. Each part is Base64URL encoded.

The header holds metadata about the token.

  • alg is the signing algorithm, for example HS256 or RS256.
  • typ is the token type, usually JWT.

The payload holds the claims, which is the data you send. Claims come in three types, registered, public and private. Here are the registered (standard) claims.

  • iss (issuer) is who created the token.
  • sub (subject) is the user ID.
  • aud (audience) is who the token is meant for.
  • exp (expiration time) is when the token expires.
  • nbf (not before) is when the token becomes valid.
  • iat (issued at) is when the token was created.
  • jti (JWT ID) is a unique ID for the token.

A signature proves the token was not changed. The server signs the header and payload with a secret or private key, then checks it on every request.

The payload is only encoded, not encrypted. So anyone can read it, and you must never put passwords in it. This program decodes a JWT payload with the standard library.

package main

import (
    "encoding/base64"
    "fmt"
    "strings"
)

func main() {
    // Build a sample token. The signature part is fake here.
    header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`))
    payload := base64.RawURLEncoding.EncodeToString([]byte(`{"sub":"42","role":"admin"}`))
    token := header + "." + payload + ".signature"

    parts := strings.Split(token, ".")
    fmt.Println("parts:", len(parts))

    decoded, err := base64.RawURLEncoding.DecodeString(parts[1])
    if err != nil {
        fmt.Println("bad payload:", err)
        return
    }
    fmt.Println("payload:", string(decoded))
}
parts: 3
payload: {"sub":"42","role":"admin"}

Q109. What is GraphQL?

GraphQL is a query language for APIs. Instead of many REST endpoints, it usually exposes a single endpoint, such as /graphql. The client asks for exactly the fields it needs, so it avoids getting too much or too little data.

query {
  user(id: "42") {
    name
    orders { id total }
  }
}

Each field in the schema is backed by a resolver function. A resolver can read a database or call another service. Then the GraphQL engine runs the resolvers, often in parallel, and merges the results into one JSON response.

In Go, the most popular library is github.com/99designs/gqlgen. It generates type-safe Go code from your schema.

Q110. What is a stateless API?

A stateless API is one where each request carries all the information needed to handle it. The server does not keep any client session between requests. For example, every request sends its own JWT in the Authorization header.

Here is why stateless APIs matter.

  • Any server can handle any request, so you can scale out by adding servers.
  • If one server fails, another can take over with no lost session.
  • There is no session lookup, so requests stay fast.
  • It fits microservices and load balancers well.

Your data still lives in a database. “Stateless” only means the server does not remember the client between calls.

Q111. What is routing in Go?

Routing maps an incoming HTTP request (method plus URL path) to the handler function that should process it. Here is how it works.

  1. The client sends a request with a method and a URL.
  2. The router matches the path and method.
  3. It calls the matching handler.
  4. The handler writes the response.

There are three common kinds of routes. A static route has a fixed path, such as /health. A dynamic route has a variable part, such as /users/{id}. Query parameters add optional inputs, such as /users?page=2.

Since Go 1.22, the standard http.ServeMux handles all of these.

package main

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

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

    // Static route
    mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "ok")
    })
    // Dynamic route with a path variable
    mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "user %s", r.PathValue("id"))
    })
    // Query parameters on a static path
    mux.HandleFunc("GET /users", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "users page %s", r.URL.Query().Get("page"))
    })

    for _, path := range []string{"/health", "/users/7", "/users?page=2"} {
        rec := httptest.NewRecorder()
        mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
        fmt.Println(path, "->", rec.Body.String())
    }
}
/health -> ok
/users/7 -> user 7
/users?page=2 -> users page 2

Q112. What is the difference between http.HandleFunc and an HTTP method?

They are different things. http.HandleFunc registers a route, mapping a URL pattern to a handler function. An HTTP method, like GET, POST, PUT or DELETE, is the type of operation the client wants on that route.

ConceptMeaning
http.HandleFuncRegisters a route (pattern to handler) in the net/http package
HTTP methodThe type of request, such as GET, POST, PUT or DELETE

Before Go 1.22, HandleFunc matched only the path. So you had to check r.Method by hand inside every handler. Since Go 1.22, you can put the method in the pattern itself, such as "POST /users". Then the mux returns 405 Method Not Allowed for other methods.

package main

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

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("POST /users", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusCreated)
        fmt.Fprint(w, "user created")
    })

    for _, method := range []string{http.MethodPost, http.MethodGet} {
        rec := httptest.NewRecorder()
        mux.ServeHTTP(rec, httptest.NewRequest(method, "/users", nil))
        fmt.Println(method, rec.Code)
    }
}
POST 201
GET 405

Frameworks like Gin and Fiber give you the same idea with methods like r.GET and app.Post.

Q113. What is a connection pool in Go?

A connection pool is a set of open connections that your app reuses, instead of opening a new one for every request. Opening a database connection is slow, because it needs a network round trip, authentication and memory. So reusing connections makes your app much faster.

Without a pool, every request opens a connection, runs a query and closes it. With a pool, connections stay open and requests borrow one and give it back.

Go’s database/sql package manages a pool for you. So sql.Open returns a pool, not a single connection, and you usually create it once and share it.

SettingWhat it does
SetMaxOpenConns(20)At most 20 connections open at once
SetMaxIdleConns(5)Keeps up to 5 idle connections ready
SetConnMaxLifetime(time.Hour)Replaces a connection after it has been open 1 hour
SetConnMaxIdleTime(10 * time.Minute)Closes connections idle for 10 minutes

Here is an example with the pgx PostgreSQL driver. It needs a driver module and a database, so it does not run here.

package main

import (
    "database/sql"
    "log"
    "os"
    "time"

    _ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver
)

func main() {
    // Read the connection string from the environment, not from code.
    db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    db.SetMaxOpenConns(20)
    db.SetMaxIdleConns(5)
    db.SetConnMaxLifetime(time.Hour)
    db.SetConnMaxIdleTime(10 * time.Minute)

    // sql.Open does not connect, so Ping checks the database is reachable.
    if err := db.Ping(); err != nil {
        log.Fatal(err)
    }
    log.Println("database connected")
}

Here are the benefits of a pool.

  • Requests are faster, because connections are reused.
  • There is less overhead from opening and closing connections.
  • It limits how many connections hit the database at once.
  • It helps the app scale under high traffic without exhausting the database.

Q114. If you store a password in a properties file, how do you read it, and should you print it?

You can read it, but you should never print or log it. Logs are copied to many systems and seen by many people. So a printed password is a leaked password.

Here is the safe approach.

  • Keep secrets out of your code and out of Git. Add files like .env to .gitignore.
  • In production, read secrets from environment variables or a secret manager, such as AWS Secrets Manager, HashiCorp Vault or Kubernetes Secrets.
  • To check a secret loaded, print only whether it is set, or a masked value.
  • Fail early with a clear message if a required secret is missing, but do not include its value.

Here is a program that reads a properties-style config and checks the password without showing it.

package main

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

// parseProperties reads key=value lines and skips comments and blanks.
func parseProperties(text string) map[string]string {
    props := make(map[string]string)
    scanner := bufio.NewScanner(strings.NewReader(text))
    for scanner.Scan() {
        line := strings.TrimSpace(scanner.Text())
        if line == "" || strings.HasPrefix(line, "#") {
            continue
        }
        key, value, found := strings.Cut(line, "=")
        if found {
            props[strings.TrimSpace(key)] = strings.TrimSpace(value)
        }
    }
    return props
}

// mask hides a secret, so logs never show the real value.
func mask(secret string) string {
    if secret == "" {
        return "(not set)"
    }
    return "********"
}

func main() {
    // In a real app this text comes from a file such as app.properties.
    config := "# database settings\ndb.user=appuser\ndb.password=S3cret!Pass\n"
    props := parseProperties(config)

    fmt.Println("db.user:", props["db.user"])
    fmt.Println("db.password:", mask(props["db.password"]))
}
db.user: appuser
db.password: ********

Many projects use a .env file with github.com/joho/godotenv and then call os.Getenv. That module is external, so this snippet does not run here.

if err := godotenv.Load(); err != nil {
    log.Println("no .env file, using real environment variables")
}

password := os.Getenv("DB_PASSWORD")
if password == "" {
    log.Fatal("DB_PASSWORD is not set")
}
log.Println("DB_PASSWORD loaded") // never log the value itself

Golang Questions and Answers on Microservices, System Design and Tools

These Golang questions and answers cover how Go fits into real systems, such as microservices, messaging, scaling and the tools around your code. Many topics are not Go-only, so each answer explains the idea and then shows where Go helps.

Q115. What are the common Go design principles?

Go is built around a few simple ideas. If you follow them, your code looks like other Go code and is easy to read.

  • Simplicity. Write plain, clear code. Go has a small language on purpose.
  • Composition over inheritance. Go has no classes or inheritance. You build types from smaller structs (embedding) and small interfaces.
  • Explicit error handling. Functions return an error value, and you check it with if err != nil.
  • Concurrency first. Goroutines and channels make concurrent code a normal part of the design.
  • Small interfaces. Interfaces like io.Reader have one or two methods, so many types can satisfy them.

Q116. What is a design pattern in Golang?

A design pattern is a reusable solution to a common software problem. Patterns come from general software engineering, so they are not specific to Go. However, Go implements them in its own simple style, with structs, interfaces, functions and channels instead of classes.

CategoryPurposeCommon patterns
CreationalCreate valuesSingleton, Factory, Builder, Functional Options
StructuralCombine typesAdapter, Decorator, Facade, Proxy
BehaviouralCommunication between partsStrategy, Observer, Command, State
Concurrency (Go style)Run work concurrentlyWorker Pool, Pipeline, Fan-in and Fan-out

The program below shows three patterns together. sync.Once gives a singleton, a function returns a type by name (factory), and an interface lets you swap payment methods at runtime (strategy).

package main

import (
    "fmt"
    "sync"
)

// Singleton: one shared Database value, created only once.
type Database struct{ name string }

var (
    once     sync.Once
    instance *Database
)

func GetDatabase() *Database {
    once.Do(func() {
        fmt.Println("creating database connection")
        instance = &Database{name: "main-db"}
    })
    return instance
}

// Factory: return a Shape based on a string.
type Shape interface{ Draw() string }

type Circle struct{}
type Square struct{}

func (Circle) Draw() string { return "drawing a circle" }
func (Square) Draw() string { return "drawing a square" }

func NewShape(kind string) Shape {
    switch kind {
    case "circle":
        return Circle{}
    case "square":
        return Square{}
    }
    return nil
}

// Strategy: pick the payment method at runtime.
type PaymentStrategy interface{ Pay(amount float64) string }

type CreditCard struct{}
type PayPal struct{}

func (CreditCard) Pay(amount float64) string { return fmt.Sprintf("paid %.2f with credit card", amount) }
func (PayPal) Pay(amount float64) string     { return fmt.Sprintf("paid %.2f with PayPal", amount) }

func main() {
    db1 := GetDatabase()
    db2 := GetDatabase()
    fmt.Println("same instance:", db1 == db2)

    fmt.Println(NewShape("circle").Draw())
    fmt.Println(NewShape("square").Draw())

    for _, method := range []PaymentStrategy{CreditCard{}, PayPal{}} {
        fmt.Println(method.Pay(99.5))
    }
}
creating database connection
same instance: true
drawing a circle
drawing a square
paid 99.50 with credit card
paid 99.50 with PayPal

Use a pattern when the same problem keeps coming back. But do not force patterns into small programs, because Go prefers the simplest code that works.

Q117. How do you consider all factors, like memory management and the database, when you design a new Go project?

Start with the big decisions, then work down to the details. Here is a checklist you can follow.

  1. Architecture. Choose a monolith, a modular monolith or microservices. Clean or hexagonal architecture keeps business logic apart from HTTP and database code.
  2. API contracts. Use gRPC for fast internal calls and REST with JSON for public APIs. Write the OpenAPI or protobuf spec on day one.
  3. Concurrency. The net/http server already runs each request in its own goroutine. Use worker pools for heavy jobs, and pass context.Context everywhere for timeouts and cancellation.
  4. Data storage. Pick the database that fits the data, as the table shows.
NeedDatabase choice
Strict ACID, complex joinsPostgreSQL, MySQL
Flexible schema, horizontal scaleMongoDB, Couchbase
Fast cache, data with expiry (TTL)Redis
AnalyticsClickHouse, BigQuery

For memory and performance, measure first and optimise second. Go has a concurrent garbage collector, so you rarely manage memory by hand.

ActionTool or detail
Avoid needless allocationsReuse buffers with sync.Pool, stream large data with io.Reader
Understand escape analysisgo build -gcflags="-m" shows stack and heap decisions
Profile earlypprof, go tool trace, allocs/op in benchmarks
Tune the GC (rarely)GOGC, GOMEMLIMIT, only after measuring

For the database, database/sql already has a connection pool. So set SetMaxOpenConns, SetMaxIdleConns and SetConnMaxLifetime. Use parameterised queries (or tools like sqlc, GORM, bun) to stop SQL injection. Then manage schema changes with migration tools such as golang-migrate or goose, and give every query a context with a timeout.

AreaRecommendation
ErrorsLibraries return errors and do not panic. Wrap with fmt.Errorf("...: %w", err)
LoggingStructured logs with the standard log/slog package (or zap, zerolog)
Metrics and tracingPrometheus client, OpenTelemetry
Health checks/healthz and /readyz endpoints, plus a DB ping
TestingTable-driven tests, testcontainers-go, go test -bench, go test -fuzz
CIgo vet, golangci-lint, govulncheck, tests, then build the image
ContainersMulti-stage Dockerfile with a distroless or scratch image
Config and secretsEnvironment variables, Vault or AWS Secrets Manager, never inside images
SecurityTLS everywhere, JWT or OAuth2 for users, mTLS for internal gRPC, gosec
Shutdownhttp.Server.Shutdown with signal.NotifyContext
Back-pressureBuffered channels, worker pools, golang.org/x/time/rate

Finally, a common folder layout looks like this.

cmd/            entry points (main packages)
internal/
    app/        business logic, service layer
    db/         SQL queries, repository layer
    transport/
        http/
        grpc/
pkg/            reusable libraries (only if others import them)
configs/        default YAML or JSON config
scripts/        CI and developer helpers
deploy/         Helm charts, Terraform

Q118. What is gRPC in Golang?

gRPC is a fast, open-source Remote Procedure Call (RPC) framework created by Google. It lets one service call a function on another service as if it were local. Services can be written in different languages, for example Go, Java or Python.

  • HTTP/2. It supports multiplexing and streaming, so it is faster than plain HTTP/1.1.
  • Protocol Buffers. You define messages and services in a .proto file. Protobuf data is binary and compact, so it is smaller and faster than JSON.
  • Code generation. protoc with the protoc-gen-go and protoc-gen-go-grpc plugins creates Go server and client code for you.
  • Four call types. Unary (one request, one response), server streaming, client streaming and bidirectional streaming.

Use gRPC for low-latency, internal microservice calls. For public browser APIs, REST with JSON is usually simpler. Here is a small .proto file.

syntax = "proto3";
package user;
option go_package = "example.com/userpb";

service UserService {
  rpc GetUser(GetUserRequest) returns (User);
}

message GetUserRequest { int64 id = 1; }
message User { int64 id = 1; string name = 2; }

Then the Go server implements the generated interface. This needs the external module google.golang.org/grpc.

type server struct {
    userpb.UnimplementedUserServiceServer
}

func (s *server) GetUser(ctx context.Context, req *userpb.GetUserRequest) (*userpb.User, error) {
    return &userpb.User{Id: req.Id, Name: "Asha"}, nil
}

func main() {
    lis, err := net.Listen("tcp", ":50051")
    if err != nil {
        log.Fatal(err)
    }
    s := grpc.NewServer()
    userpb.RegisterUserServiceServer(s, &server{})
    log.Fatal(s.Serve(lis))
}

Q119. What is RabbitMQ?

RabbitMQ is an open-source message broker. It lets services talk to each other by sending and receiving messages asynchronously, so they do not call each other directly.

It works in three steps. First, a producer sends a message to an exchange. Next, the exchange routes it into one or more queues. Then a consumer reads the message from the queue and acknowledges it when the work is done.

  • It decouples services and handles background work.
  • It buffers messages when consumers are slow.
  • Durable queues and acknowledgements mean messages are not lost when a consumer is down.
  • It supports patterns such as work queues, publish and subscribe, routing and topics.

Common uses are sending emails in the background, image or video processing, and notifications. In Go, the official client is github.com/rabbitmq/amqp091-go.

Q120. What is Kafka and why is it used?

Apache Kafka is an open-source, distributed event streaming platform. It handles real-time data streams at a very large scale. Think of it as a durable log that many services can write to and read from.

Here is how it works.

  • Producers write messages (events) to a topic.
  • Brokers are Kafka servers that store the topics.
  • Each topic is split into partitions, so many consumers can read in parallel.
  • Consumers read messages. Consumers in the same consumer group share the partitions between them.
  • Kafka keeps messages for a set time, so consumers can replay old events.

Teams use Kafka for real-time streaming of logs, metrics and transactions. It also powers event-driven microservices and moves data between systems, for example MySQL to Kafka to Elasticsearch. Log aggregation and live analytics are other common uses.

KafkaRabbitMQ
Event log, messages kept for replayQueue, message removed after ack
Very high throughputFlexible routing
Good for streams and analyticsGood for task queues

In Go, popular clients are github.com/segmentio/kafka-go, github.com/twmb/franz-go and confluent-kafka-go. This short producer uses kafka-go.

writer := &kafka.Writer{
    Addr:  kafka.TCP("localhost:9092"),
    Topic: "orders",
}
defer writer.Close()

err := writer.WriteMessages(context.Background(),
    kafka.Message{Key: []byte("order-1"), Value: []byte(`{"total": 250}`)},
)
if err != nil {
    log.Fatal(err)
}

Q121. What are monolithic and microservice applications, and what is the difference between them?

A monolithic application is one unified program. The UI, business logic and data access are built and deployed together, often as a single binary. So it is simple to start, but every change means redeploying the whole app.

A microservice application is split into small, independent services. Each one owns one business function, for example an Order Service, a Payment Service and an Inventory Service. They talk through REST, gRPC or message queues like Kafka and RabbitMQ.

AspectMonolithicMicroservices
CodebaseOneOne per service
DeploymentWhole app at onceEach service on its own
ScalingWhole app scales togetherScale only busy services
DatabaseUsually one shared databaseEach service owns its data
CouplingTightLoose
Tech stackUsually oneCan differ per service
Fault isolationOne bug can crash everythingA failure stays in one service
Team speedSlower for large teamsSmall teams work in parallel
ComplexitySimple to start, hard at large scaleHarder to start (network, monitoring), easier at large scale

A good rule is to start with a well-structured monolith. Then split out services when you have a clear reason.

Q122. What coding practices should you follow in Golang?

Following common Go practices makes your code easy for other Go developers to read. Start with naming.

ItemConventionExample
Packageshort, lower case, no underscoresuserauth
Unexported namescamelCasetotalCount, getUserData()
Exported namesPascalCaseGetUser()
ConstantscamelCase or PascalCase (not UPPER_SNAKE_CASE)maxRetry, DefaultLimit
Acronymskeep one caseuserID, ServeHTTP

The old answer suggested UPPER_SNAKE_CASE for constants. However, Go style uses normal camelCase or PascalCase for constants too.

  1. Format with gofmt. Run go fmt ./... or gofmt. It uses tabs and aligns your code automatically.
  2. Keep functions small. Split one huge ProcessOrder into ValidateOrder, SaveOrder and SendOrderEmail.
  3. Handle every error. Return early instead of nesting, and wrap errors with context using %w.
  4. Avoid global state. Pass dependencies in through constructors.
  5. Pass context. Give API and database functions a ctx context.Context as the first parameter.
  6. Name packages by purpose. Prefer logger, validation or repository over a catch-all utils package.
  7. Write tests. Run go test ./... and use table-driven tests.
  8. Add interfaces only when needed. Define small interfaces where they are used, not “just in case”.
  9. Stay concurrency safe. Protect shared data with a mutex or channels, and run go test -race ./....
  10. Lint. Run go vet and a linter like staticcheck or golangci-lint.

Here are early return, error wrapping and dependency injection in one snippet.

type Service struct {
    db *sql.DB
}

func NewService(db *sql.DB) *Service { return &Service{db: db} }

func (s *Service) GetUser(ctx context.Context, id int) (User, error) {
    var u User
    err := s.db.QueryRowContext(ctx, "SELECT id, name FROM users WHERE id = $1", id).Scan(&u.ID, &u.Name)
    if err != nil {
        return User{}, fmt.Errorf("get user %d: %w", id, err)
    }
    return u, nil
}
DoAvoid
Use slices for listsCopying large arrays by value
Preallocate with make([]T, 0, n) when you know the sizeGrowing slices one item at a time in hot loops
Reuse objects with sync.Pool in hot pathsNeedless allocations
Profile before you switch JSON librariesGuessing where the slow part is
Use goroutines for I/O work, with limitsStarting unbounded goroutines

Q123. What is the use of SonarQube?

SonarQube is a code quality and security tool. It scans your source code, including Go, and reports problems before they reach production.

CategoryExamples
BugsNil pointer issues, resource leaks
VulnerabilitiesSQL injection, hardcoded credentials
Code smellsDuplicated code, long or complex functions
Test coverageHow much code your unit tests cover
MaintainabilityHigh complexity, unused code
Security hotspotsCode that needs a security review

Teams use it to keep code clean and to find security risks early. It also enforces shared coding standards and tracks technical debt over time. A quality gate can fail the build when new code breaks the rules.

SonarQube runs inside CI/CD pipelines such as Jenkins, GitHub Actions, GitLab CI, Azure DevOps and Bitbucket Pipelines. It scans every commit or pull request. For Go, you pass a coverage file to it, as shown below.

go test ./... -coverprofile=coverage.out
sonar-scanner -Dsonar.projectKey=my-go-app -Dsonar.go.coverage.reportPaths=coverage.out

Q124. Why use rebase in Git?

You use git rebase to keep commit history clean and linear. Rebase takes your commits and replays them on top of another branch, as if you wrote them later. So the history reads as one straight line, with no extra merge commits.

git switch feature
git fetch origin
git rebase origin/main          # replay feature commits on top of the latest main
git rebase -i HEAD~3            # squash or edit your last 3 commits
git push --force-with-lease     # needed after rebasing a pushed branch

Rebase rewrites commit hashes. So never rebase a shared branch that other people already use. Use git merge there instead.

The old answer also mentioned “peek”. This is an informal word, not a Git command. It means looking at something without changing it.

To peek atCommand
Commit historygit log --oneline
Working changesgit status, git diff
One commitgit show <commit-hash>
A file on another branchgit show main:file.txt

Q125. What is an API gateway?

An API gateway is a single entry point that sits in front of your microservices. It receives client requests and routes each one to the right service. It also handles shared concerns like authentication, rate limiting, caching, logging and load balancing.

  • Central security. Check tokens once at the gateway, not in every service.
  • Easier monitoring. All traffic passes one place.
  • Better scaling. It spreads load and can cache responses.
  • Cleaner clients. Clients call one URL instead of many services.

Popular gateways include NGINX, Kong, AWS API Gateway, Apigee and Traefik. You can also build a simple one in Go with net/http/httputil.ReverseProxy. In fact, Traefik itself is written in Go.

Q126. How do you stop one microservice from calling another one repeatedly or too many times?

You combine a few protection patterns. Each one solves a different part of the problem.

  • Circuit breaker (most important). It tracks failures. After too many, it “opens” and stops calls for a while, so the failing service can recover. This also prevents cascading failures. Go libraries include sony/gobreaker and failsafe-go.
  • Rate limiting. It caps how many requests per second a service may send or receive. In Go, use golang.org/x/time/rate, or set limits in an API gateway or Redis.
  • Retry with backoff. Retry only temporary errors, wait longer each time, add jitter and set a maximum number of tries.
  • Timeouts with context. Every outgoing call needs context.WithTimeout, so a slow service cannot block you forever.
  • Caching. If the data rarely changes, keep it in Redis or an in-memory cache, so you do not call the other service again.

This program builds a tiny circuit breaker. After two failures it opens and rejects calls without contacting the service.

package main

import (
    "errors"
    "fmt"
)

var ErrOpen = errors.New("circuit open: call skipped")

// CircuitBreaker stops calls after too many failures in a row.
type CircuitBreaker struct {
    failures    int
    maxFailures int
}

func (cb *CircuitBreaker) Call(fn func() error) error {
    if cb.failures >= cb.maxFailures {
        return ErrOpen // do not even call the service
    }
    if err := fn(); err != nil {
        cb.failures++
        return err
    }
    cb.failures = 0 // success resets the count
    return nil
}

func main() {
    cb := &CircuitBreaker{maxFailures: 2}
    callPayment := func() error { return errors.New("payment service timeout") }

    for i := 1; i <= 4; i++ {
        fmt.Printf("call %d: %v\n", i, cb.Call(callPayment))
    }
}
call 1: payment service timeout
call 2: payment service timeout
call 3: circuit open: call skipped
call 4: circuit open: call skipped

A real breaker also has a “half-open” state. After a cool-down time, it lets one test call through, and if that succeeds it closes again.

Q127. What are the common Docker commands?

Docker packages your Go app and its dependencies into a container image. These are the commands you use most.

docker --version                    # show the installed version
docker pull nginx                   # download an image
docker images                       # list local images
docker build -t my-go-app .         # build an image from a Dockerfile
docker run -d -p 8080:80 nginx      # run in the background, host port 8080 to container port 80
docker ps                           # list running containers (add -a for all)
docker logs -f <container>          # follow container logs
docker exec -it <container> sh      # open a shell inside a container
docker stats                        # live CPU and memory usage
docker stop <container>             # stop a container
docker rm <container>               # remove a stopped container
docker compose up -d                # start all services in compose.yaml
docker compose down                 # stop and remove them

The old docker-compose tool (with a hyphen) is replaced by the docker compose plugin. Also, a multi-stage Dockerfile keeps Go images very small, as shown here.

FROM golang:1.27 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /app ./cmd/server

FROM gcr.io/distroless/static
COPY --from=build /app /app
ENTRYPOINT ["/app"]

Q128. What is sharding?

Sharding splits data into smaller, independent parts called shards. Each shard holds only part of the data, so the system can scale horizontally. For example, 1 million users could be split by ID range into four shards of 250,000 users each.

When a request comes in, you first work out which shard holds the key. Then you read or write only that shard.

In Go, sharding is used in two places. At the database level, it spreads data across many servers. Inside one program, it splits a busy map into many smaller maps, each with its own lock. This reduces lock contention, because goroutines working on different shards do not wait for each other.

package main

import (
    "fmt"
    "hash/fnv"
    "sync"
)

const numShards = 4

type shard struct {
    mu   sync.RWMutex
    data map[string]string
}

// ShardedCache spreads keys over several maps, each with its own lock.
type ShardedCache struct {
    shards [numShards]*shard
}

func NewShardedCache() *ShardedCache {
    c := &ShardedCache{}
    for i := range c.shards {
        c.shards[i] = &shard{data: make(map[string]string)}
    }
    return c
}

// shardIndex hashes the key so the same key always goes to the same shard.
func shardIndex(key string) int {
    h := fnv.New32a()
    h.Write([]byte(key))
    return int(h.Sum32() % numShards)
}

func (c *ShardedCache) Set(key, value string) {
    s := c.shards[shardIndex(key)]
    s.mu.Lock()
    s.data[key] = value
    s.mu.Unlock()
}

func (c *ShardedCache) Get(key string) (string, bool) {
    s := c.shards[shardIndex(key)]
    s.mu.RLock()
    defer s.mu.RUnlock()
    v, ok := s.data[key]
    return v, ok
}

func main() {
    cache := NewShardedCache()
    var wg sync.WaitGroup
    for i := 1; i <= 100; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            key := fmt.Sprintf("user%d", i)
            cache.Set(key, fmt.Sprintf("name-%d", i))
        }()
    }
    wg.Wait()

    v, ok := cache.Get("user42")
    fmt.Println(v, ok)
    total := 0
    for _, s := range cache.shards {
        total += len(s.data)
    }
    fmt.Println("total keys:", total)
}
name-42 true
total keys: 100

Across servers, consistent hashing is common, because it moves only a few keys when you add or remove a shard.

AdvantagesDisadvantages
Higher concurrency, less lock contentionMore complex code
Scales across many machinesEvery lookup needs a shard calculation
Better CPU useRebalancing is hard without consistent hashing
Spreads loadCross-shard queries and transactions are harder

Use sharding when one lock or one database is a real bottleneck, such as in caches, rate limiters or session stores. But avoid it for small data or low concurrency, because the extra complexity is not worth it.

Q129. What is cherry-pick in Git?

git cherry-pick copies one specific commit from another branch onto your current branch. You get that single change without merging the whole branch. For example, you can move a bug fix from develop into a release branch.

git switch release
git cherry-pick a1b2c3d             # apply one commit
git cherry-pick a1b2c3d e4f5g6h     # apply several commits
git cherry-pick --continue          # after you fix a conflict
git cherry-pick --abort             # cancel and go back

The new commit gets a new hash, because it is a copy. So use cherry-pick for small, targeted fixes, not to move large features.

Q130. How do you handle API failure?

You plan for failure, because networks and other services will fail sometimes.

  • Timeouts. Give every call a deadline with context.WithTimeout.
  • Retries with backoff. Retry only temporary errors such as timeouts or HTTP 503.
  • Circuit breaker. Stop calling a service that keeps failing.
  • Clear error messages. Return correct HTTP status codes and wrap Go errors with %w, so the cause is easy to find.
  • Fallbacks. Serve cached data or a default response when possible.
  • Logging and monitoring. Log errors with a request ID and track error rates, so you see problems early.

Q131. What is a retry mechanism?

A retry mechanism automatically tries an operation again when it fails. It helps with temporary problems such as network glitches, timeouts and an overloaded server. However, do not retry permanent errors like HTTP 400 or a wrong password.

Good retries use exponential backoff. So each wait is longer than the last, for example 100 ms, 200 ms, then 400 ms. Also add random jitter in real code, set a maximum number of attempts, and only retry operations that are safe to repeat (idempotent).

package main

import (
    "errors"
    "fmt"
    "time"
)

// retry calls fn up to maxAttempts times, doubling the wait after each failure.
func retry(maxAttempts int, baseDelay time.Duration, fn func() error) error {
    delay := baseDelay
    var err error
    for attempt := 1; attempt <= maxAttempts; attempt++ {
        if err = fn(); err == nil {
            return nil
        }
        fmt.Printf("attempt %d failed: %v, waiting %v\n", attempt, err, delay)
        time.Sleep(delay)
        delay *= 2
    }
    return fmt.Errorf("all %d attempts failed: %w", maxAttempts, err)
}

func main() {
    calls := 0
    fetchOrder := func() error {
        calls++
        if calls < 3 {
            return errors.New("service unavailable")
        }
        return nil
    }

    if err := retry(5, 10*time.Millisecond, fetchOrder); err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("success after", calls, "calls")
}
attempt 1 failed: service unavailable, waiting 10ms
attempt 2 failed: service unavailable, waiting 20ms
success after 3 calls

Q132. How do you handle high traffic?

You spread the load, reduce work per request and add capacity when needed.

  • Load balancing. Spread requests across many app instances.
  • Caching. Keep hot data in Redis or a CDN, so fewer requests hit the database.
  • Database indexing. Add indexes for frequent queries, and use read replicas.
  • Horizontal scaling. Add more instances, often with auto scaling.
  • Async work. Push slow tasks to a queue like Kafka, RabbitMQ or SQS.
  • Rate limiting. Protect the system from floods of requests.

Go helps here because each request runs in a cheap goroutine. So one Go instance can serve many thousands of concurrent requests.

Q133. How do you debug production issues?

You rely on the data your system already records, because you cannot attach a debugger in production.

  • Logs. Use structured logs (for example log/slog) with a request ID, so you can follow one request.
  • Monitoring and metrics. Watch error rate, latency and resource use in tools like CloudWatch, Prometheus and Grafana.
  • Tracing. OpenTelemetry shows how a request moves across services and where time is spent.
  • Profiling. Go’s net/http/pprof shows CPU, memory and goroutine profiles from a running service.

Then reproduce the issue in a staging environment, write a test that fails, fix it and deploy the change.

Q134. How do you ensure code quality?

You use several checks together, and you automate as many as you can.

  • Unit tests. Write table-driven tests and run go test -race -cover ./....
  • Code reviews. Every change gets reviewed by another developer.
  • Linting. Run gofmt, go vet, staticcheck or golangci-lint.
  • Security scans. Use govulncheck and tools like SonarQube.
  • CI pipeline. Run all of these on every pull request, and block the merge when a check fails.

Q135. Why is load balancing needed, and how does it work?

A load balancer spreads incoming requests across several backend servers. You need one for four reasons.

  • No single server gets overloaded.
  • Response time improves.
  • You get high availability, because traffic skips unhealthy servers.
  • Adding servers lets you handle more traffic.

The flow is simple. First, the client sends a request. Next, the load balancer picks a healthy server. Then it forwards the request and sends the response back.

AlgorithmHow it picks a server
Round robinEach server in turn
Least connectionsServer with the fewest active connections
IP hashSame client IP goes to the same server
WeightedMore powerful servers get more traffic

You can also write a load balancer in Go, because net/http/httputil.ReverseProxy does the forwarding. This program shows the round robin choice. It uses an atomic counter, so it is safe across goroutines.

package main

import (
    "fmt"
    "sync/atomic"
)

type RoundRobin struct {
    servers []string
    next    atomic.Uint64
}

// Pick returns the next server in turn.
func (rr *RoundRobin) Pick() string {
    n := rr.next.Add(1) - 1
    return rr.servers[n%uint64(len(rr.servers))]
}

func main() {
    lb := &RoundRobin{servers: []string{"app1:8080", "app2:8080", "app3:8080"}}
    for req := 1; req <= 5; req++ {
        fmt.Printf("request %d -> %s\n", req, lb.Pick())
    }
}
request 1 -> app1:8080
request 2 -> app2:8080
request 3 -> app3:8080
request 4 -> app1:8080
request 5 -> app2:8080

Q136. How do you design a high-scale, low-latency system?

You remove slow work from the request path and scale out instead of up.

  • Caching. Redis or in-memory caches answer hot reads quickly.
  • CDN. Serve static files and images close to users.
  • Load balancing and horizontal scaling. Run many stateless instances behind a load balancer.
  • Async processing. Send slow work to Kafka or a queue and return quickly.
  • Database design. Add indexes, read replicas and, at very large scale, sharding.
  • Efficient calls. Use gRPC, connection pooling and timeouts between services.
  • Measure. Track p95 and p99 latency, not just the average.

Go fits well because it has fast startup, low memory use and cheap goroutines.

Q137. If you get 1,000 requests, which Go features and AWS services can you use to handle them?

Here is a short interview answer. Run several instances of the Go app behind an AWS Application Load Balancer. Each HTTP request runs in its own goroutine, so 1,000 concurrent requests are normal for Go. Then add a database connection pool, a Redis cache and a queue for slow work, with auto scaling for traffic spikes.

On the Go side, use these tools.

  • Goroutines. The net/http server already starts one per request.
  • Worker pool. Limit CPU-heavy background jobs to a fixed number of workers.
  • Connection pool. Set db.SetMaxOpenConns(100) and db.SetMaxIdleConns(20).
  • Context timeouts. Use context.WithTimeout, so no request hangs forever.

This worker pool sends 6 jobs to 3 workers and collects the results in order.

package main

import (
    "fmt"
    "sync"
)

func worker(jobs <-chan int, results []int, wg *sync.WaitGroup) {
    defer wg.Done()
    for id := range jobs {
        results[id] = id * id // each job writes its own slot, so no race
    }
}

func main() {
    const numJobs, numWorkers = 6, 3
    jobs := make(chan int, numJobs)
    results := make([]int, numJobs)

    var wg sync.WaitGroup
    for w := 0; w < numWorkers; w++ {
        wg.Add(1)
        go worker(jobs, results, &wg)
    }
    for id := 0; id < numJobs; id++ {
        jobs <- id
    }
    close(jobs)
    wg.Wait()

    fmt.Println("results:", results)
}
results: [0 1 4 9 16 25]

On the AWS side, these services help.

AWS serviceRole
Application Load Balancer (ALB)Spreads requests across Go instances
Auto Scaling, ECS or EKSAdds instances or containers when traffic grows
RDS or AuroraManaged database with read replicas and backups
ElastiCache (Redis)Caches hot data and reduces DB load
S3Stores files, images and logs, not on the server disk
SQSQueues slow jobs like emails and reports for background workers
CloudWatchLogs, metrics and alarms

Q138. What is ECS?

Amazon ECS (Elastic Container Service) is a fully managed AWS service for running Docker containers. It deploys, runs, scales and restarts your containers, so you do not manage the orchestration yourself.

Without ECS, you create an EC2 instance, install Docker and start containers by hand. You also restart crashed containers and scale them manually. With ECS, you push your Go image to Amazon ECR and describe it in a task definition. Then an ECS service keeps the right number of tasks running.

  • ECS restarts tasks that crash or fail health checks.
  • Tasks scale automatically based on CPU or request count.
  • An Application Load Balancer can route traffic to the tasks.
  • You can run them on Fargate (serverless, no servers to manage) or on your own EC2 instances.

ECS is simpler than Kubernetes (EKS), so it is a common choice for Go microservices on AWS.

Q139. What is a URL shortener?

A URL shortener turns a long URL into a short, unique one. For example, https://www.example.com/products/mobile/iphone?color=black&storage=256GB becomes https://short.ly/aB12Cd. When someone opens the short link, the service redirects them to the original URL.

It works in two flows.

  • Create. The user sends a long URL. The service makes a unique code, saves code -> long URL in a database and returns the short link.
  • Redirect. A user opens GET /aB12Cd. The service looks up the code and replies with an HTTP 301 or 302 redirect.

There are three common ways to make the code.

  1. Base62 encoding (most common). Take a unique number, such as an auto-increment ID, and encode it with 0-9, A-Z and a-z. Seven characters give over 3.5 trillion codes.
  2. Random string. Generate random characters and check the database for clashes.
  3. Hashing. Hash the URL with MD5 or SHA-256 and keep the first few characters. Then handle collisions.

This Go program encodes and decodes IDs with Base62.

package main

import (
    "fmt"
    "strings"
)

const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

// encode turns a numeric ID into a short Base62 code.
func encode(id uint64) string {
    if id == 0 {
        return string(alphabet[0])
    }
    var b []byte
    for id > 0 {
        b = append(b, alphabet[id%62])
        id /= 62
    }
    // digits were built in reverse order, so flip them
    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
        b[i], b[j] = b[j], b[i]
    }
    return string(b)
}

// decode turns a Base62 code back into the numeric ID.
func decode(code string) uint64 {
    var id uint64
    for _, c := range code {
        id = id*62 + uint64(strings.IndexRune(alphabet, c))
    }
    return id
}

func main() {
    for _, id := range []uint64{1, 61, 62, 125000, 3521614606207} {
        code := encode(id)
        fmt.Printf("id %d -> %s -> %d\n", id, code, decode(code))
    }
}
id 1 -> 1 -> 1
id 61 -> z -> 61
id 62 -> 10 -> 62
id 125000 -> WW8 -> 125000
id 3521614606207 -> zzzzzzz -> 3521614606207

At scale, you also add a Redis cache for popular links, rate limiting, link expiry and click analytics.

Q140. Why are microservices used in Golang, and what is their main purpose?

The main purpose of microservices is to break a large application into small, independent services. Each service handles one business capability, such as users, products or orders.

  • Independent scaling. Suppose the Order Service gets 5,000 requests per minute and the User Service gets 100. Then you can run ten Order instances and only one User instance, which saves money.
  • Fault isolation. If the Notification Service crashes, the User, Product and Order services keep working.
  • Technology choice. One service can use Go, while another uses Python for machine learning.
  • Faster teams. Team A owns the User Service and Team B owns the Order Service, so they ship in parallel.

Go is a popular choice for microservices for several reasons.

  • It compiles to fast native code.
  • Goroutines handle many concurrent requests cheaply.
  • It uses little memory and starts quickly, which suits containers.
  • It builds a single static binary, so deployment is simple.
  • The standard library includes HTTP, JSON and networking support.

Services talk to each other through REST APIs, gRPC, or message queues such as Kafka, RabbitMQ and Amazon SQS.

Concurrency vs Parallelism in Go

Interviewers ask this comparison so often that it deserves a quick summary at the end of these Golang questions and answers. The table below shows the difference in one view.

Golang questions and answers comparison of concurrency and parallelism
Concurrency means dealing with many tasks at once, while parallelism means doing many tasks at the same moment on many CPU cores.
FeatureConcurrencyParallelism
MeaningDealing with many tasks at onceDoing many tasks at the same moment
Needs many CPU coresNoYes
Go toolGoroutines and channelsGoroutines plus GOMAXPROCS above 1
ExampleA web server handling many requestsSplitting a big calculation across cores
GoalGood structure and responsivenessFaster total work

So Go makes concurrency easy to write, and the runtime turns it into parallelism when your machine has more than one core.

Common Mistakes When Answering Golang Questions

  • Mixing Go with other languages: Go has no classes, no while loop, no inheritance and no === operator.
  • Forgetting that slices share arrays: always mention length, capacity and append.
  • Writing to a map from many goroutines: say you would protect it with a mutex.
  • Ignoring errors: never answer with code that drops an err without a reason.
  • Leaking goroutines: explain how each goroutine stops, with context or a done channel.

Best Practices for Your Go Interview Answers

  • Start with a one-line definition, then give a small example.
  • Mention trade-offs, such as mutex vs channel or Gin vs Fiber.
  • Name the tools you use, such as go vet, the race detector and pprof.
  • Use real numbers from your projects, such as response times or memory saved.
  • Keep code idiomatic: check errors right away and format with gofmt.

Practice Task

Pick ten questions from different sections, for example Q1, Q25, Q40, Q50, Q60, Q75, Q90, Q100, Q120 and Q135. Answer each one out loud in under one minute, then compare with the answer here. Hint: record yourself, because hearing your own answer shows where you hesitate.

Official Resources

Quick Recap

  • These Golang questions and answers cover 140 questions in eight clear sections.
  • Every full code example was run, and its output is shown.
  • Wrong or outdated answers from the old post were corrected for Go 1.27.
  • Concurrency questions are the largest section, because interviewers ask them most.
  • Practise out loud and run the code, because that is how answers stick.

What’s Next?

Go deeper one topic at a time with the 29 topic posts in our Go topic-wise interview hub. For live coding rounds, practise the Go coding interview programs.