🎓 A1Learner
🔍

Home / Blog / Programming / Go

Top 50 Go Interview Questions with Answers

Programming · Go · 29 min read

Fifty Go interview questions with answers, from first programs to goroutines. Every program ran on Go 1.25.4, and the page shows the real output.

How this sheet works

This page asks fifty Go interview questions, in groups by topic. Basics open the page. Slices, maps, and structs come next. Interfaces, errors, and packages follow, then goroutines and channels. The final six questions are small coding tasks, written out by hand.

Go 1.25.4 compiled and ran every program below. Each run's printed lines appear on the page exactly as they came out. Every printed line below came from a real run. One program writes a file into a fresh temporary folder and reads it back, so no path appears in the output. The channel and worker programs fix their print order, so the printed lines never change. A final program is meant to fail. It declares a variable and never uses it. The compiler's own error lines stand in place of output.

Work through one question at a time. Cover the answer and speak your own first, then read the page version. Type each program out and run it yourself. Saying an answer and running a program both fix it in memory better than reading alone.

The Go track here holds 100 lessons: 38 in Beginner, 34 in Intermediate, and 28 in Advanced. A wrong answer points at the lesson that covers the idea. Answers that draw on two lessons name both.

Two honest limits. Reflection, unsafe code, and profiling are not in this sheet: they live in Go Advanced and need their own study. The HTTP answer serves one request from a test server. The Go HTTP Server lesson covers a real server.

1. What is Go, and what is it used for?

Go is a programming language. Google created it in 2009. It compiles to fast machine code. It keeps its syntax small and plain.

Go suits servers and network services. It suits command-line tools and cloud systems. Its goroutines handle many tasks at once. Its standard library covers HTTP, JSON, and files.

The Go Introduction lesson covers the language and its main uses. The Go Get Started lesson shows how to set it up.

package main

import "fmt"

func main() {
	fmt.Println("Go is a compiled language.")
	fmt.Println("It is used for servers and tools.")
	fmt.Println("It starts fast and runs fast.")
}

Output:
Go is a compiled language.
It is used for servers and tools.
It starts fast and runs fast.

2. What does a first Go program look like?

A first Go program has three parts. The package line names the package. The import line brings in fmt. The main function holds the code that runs.

The program prints a greeting with fmt.Println. The main function runs when the program starts. Every runnable program has exactly one main function. The code stays short and readable.

The Go Introduction lesson walks through a first program. The Go Output lesson covers printing text.

package main

import "fmt"

func main() {
	fmt.Println("Hello, World!")
	fmt.Println("This program has three parts.")
	fmt.Println("A package, an import, and a main function.")
}

Output:
Hello, World!
This program has three parts.
A package, an import, and a main function.

3. How do you run a Go program?

A Go program runs from the command line. The file holds the source code. The go tool compiles and runs it.

The command go run main.go compiles the file and runs it at once. The command go build makes a binary file instead. The binary runs on its own without the go tool. The file name main.go is the usual name for a first program.

The Go Get Started lesson shows the commands to run a program. The Go Output lesson shows what the program prints.

package main

import "fmt"

func main() {
	fmt.Println("Hello, World!")
}

Output:
Hello, World!

4. What is the go.mod file, and what does it do?

The go.mod file defines a Go module. A module is a set of packages with one version history. The file sits at the root of the project.

The module line names the module. The go line names the Go version. The require lines list outside packages and their versions. The go tool reads this file to fetch the right code.

The Go Modules lesson covers modules and the go.mod file. The Go Get Started lesson shows how a project starts.

module hello

go 1.25

5. What is a variable in Go?

A variable is a named box for a value. The name stays fixed. The value can change. Each variable has a type.

The var keyword declares a variable with a type. The short form := declares it and sets a value. The type follows from the value with :=. A variable must be used after it is declared.

The Go Variables lesson works through each kind with its own short program.

package main

import "fmt"

func main() {
	var name string = "Ada"
	var age int = 36
	price := 19.99
	fmt.Println(name)
	fmt.Println(age)
	fmt.Println(price)
}

Output:
Ada
36
19.99

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

var and := both declare variables. var states the type in words. := lets the compiler work out the type from the value.

var works at the top level of a file and inside functions. := works only inside functions. var can declare a variable with no value. := always needs a value on the same line.

A declared variable that is never used stops the build. The compiler prints this error: "./bad.go:4:2: declared and not used: count". The fix is to use the variable or remove it.

The Go Variables lesson shows both forms side by side. The Go Scope lesson covers where each form can be used.

package main

import "fmt"

func main() {
	var count int = 10
	message := "ready"
	fmt.Println(count)
	fmt.Println(message)
}

Output:
10
ready

package main

func main() {
	count := 10
}

Compile error:
# command-line-arguments
./bad.go:4:2: declared and not used: count

7. What are the basic data types in Go?

A data type says what kind of value a variable holds. Go checks types when the code compiles. A value cannot change its type by itself.

The basic types are int, float64, string, and bool. An int holds a whole number. A float64 holds a number with a decimal point. A string holds text. A bool holds true or false.

The Go Data Types lesson lists each basic type. The Go Numbers lesson covers integers and floats in detail.

package main

import "fmt"

func main() {
	var age int = 36
	var price float64 = 19.99
	var name string = "Ada"
	var active bool = true
	fmt.Printf("%T %v\n", age, age)
	fmt.Printf("%T %v\n", price, price)
	fmt.Printf("%T %v\n", name, name)
	fmt.Printf("%T %v\n", active, active)
}

Output:
int 36
float64 19.99
string Ada
bool true

8. What is a constant, and what is iota?

A constant is a value that never changes. It is set once when the code is written. It cannot be given a new value later.

The const keyword declares a constant. iota counts inside a const block. It starts at 0 and rises by 1 for each line. It gives a neat way to number a set of related values.

The Go Constants lesson declares constants with examples. The Go Enums lesson uses iota to number a set of values.

package main

import "fmt"

const pi = 3.14

const (
	Sunday = iota
	Monday
	Tuesday
)

func main() {
	fmt.Println(pi)
	fmt.Println(Sunday)
	fmt.Println(Monday)
	fmt.Println(Tuesday)
}

Output:
3.14
0
1
2

9. How do you convert between types in Go?

Type conversion turns a value of one type into a value of another type. Go never converts types on its own. The code must ask for the change in words.

The conversion names the target type and wraps the value. An int becomes a float64 with float64(price). A float64 becomes an int with int(temp). The decimal part is dropped when a float becomes an int.

The Go Type Conversion lesson shows conversions with examples. The Go Data Types lesson lists the types that can convert.

package main

import "fmt"

func main() {
	price := 100
	total := float64(price) * 1.5
	fmt.Println(total)
	temp := 36.6
	whole := int(temp)
	fmt.Println(whole)
}

Output:
150
36

10. What are Go operators?

An operator is a symbol that does one job on values. Go has operators for maths, comparison, and logic. Each operator takes values and gives back a result.

The maths operators are + - * / and %. The comparison operators are == != < > <= and >=. The logic operators are && || and !. A comparison gives back true or false.

The Go Operators lesson covers each group with examples. The Go Booleans lesson covers the true and false values they work on.

package main

import "fmt"

func main() {
	fmt.Println(10 + 3)
	fmt.Println(10 - 3)
	fmt.Println(10 * 3)
	fmt.Println(10 / 3)
	fmt.Println(10 % 3)
	fmt.Println(10 > 3)
	fmt.Println(true && false)
}

Output:
13
7
30
3
1
true
false

11. How does if...else work in Go?

if...else runs code only when a test is true. The test sits after the if keyword. The code for the true case sits in braces.

else runs when the test is false. else if adds a second test. The tests run in order from top to bottom. The first true test wins.

The Go If and Else lesson shows each branch with examples. The Go Booleans lesson covers the true and false tests.

package main

import "fmt"

func main() {
	score := 85
	if score >= 90 {
		fmt.Println("Grade A")
	} else if score >= 80 {
		fmt.Println("Grade B")
	} else {
		fmt.Println("Grade C")
	}
}

Output:
Grade B

12. How does a switch statement work in Go?

A switch statement picks one case from many. It tests one value against a list. The matching case runs. The other cases are skipped.

Each case names one value to match. A default case catches the values that match nothing else. Go leaves a case on its own after it runs. There is no fallthrough unless the code asks for it.

The Go Switch lesson shows a switch with several cases. The Go If and Else lesson covers the same choice written with if.

package main

import "fmt"

func main() {
	day := 3
	switch day {
	case 1:
		fmt.Println("Monday")
	case 2:
		fmt.Println("Tuesday")
	case 3:
		fmt.Println("Wednesday")
	default:
		fmt.Println("Another day")
	}
}

Output:
Wednesday

13. How does a for loop work in Go?

A for loop repeats a block of code. Go has only the for loop. It covers counting, testing, and ranging over values.

The common form has three parts. The first part sets a counter. The second part tests the counter. The third part moves the counter on. The loop stops when the test turns false.

The Go For Loop lesson shows the counting form with examples. The Go Range lesson covers looping over a slice or map.

package main

import "fmt"

func main() {
	sum := 0
	for i := 1; i <= 5; i++ {
		sum += i
	}
	fmt.Println(sum)
}

Output:
15

14. What are break and continue for?

break and continue change a loop while it runs. Both sit inside a for loop. Each one does a different job.

break stops the loop at once. The code after the loop runs next. continue skips the rest of the current round. The loop moves on to the next round.

The Go Break and Continue lesson shows both words in a loop. The Go For Loop lesson covers the loops they sit inside.

package main

import "fmt"

func main() {
	for i := 1; i <= 10; i++ {
		if i%2 == 0 {
			continue
		}
		if i > 7 {
			break
		}
		fmt.Println(i)
	}
}

Output:
1
3
5
7

15. What is a function in Go?

A function is a named set of steps the program can run on demand. It takes inputs and gives back a result. The same function can run many times with different inputs.

The func keyword starts a function. The name follows the keyword. The inputs sit in brackets after the name. The return type sits after the brackets.

The Go Functions lesson defines a function with examples. The Go Scope lesson covers where a function can be called.

package main

import "fmt"

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

func main() {
	fmt.Println(add(3, 4))
}

Output:
7

16. How does a function return more than one value?

A Go function can return more than one value. The return types sit in brackets after the inputs. The return line lists one value for each type.

The caller takes the values in the same order. Each value can go to its own variable. The error value is often the last one. The caller checks it before using the rest.

The Go Multiple Returns lesson shows a function with two returns. The Go Functions lesson covers single returns first.

package main

import "fmt"

func divide(a int, b int) (int, int) {
	return a / b, a % b
}

func main() {
	quotient, remainder := divide(17, 5)
	fmt.Println(quotient)
	fmt.Println(remainder)
}

Output:
3
2

17. What is recursion, and when does it help?

Recursion means a function solving a problem by calling itself with a smaller version of the same problem. Every call takes a smaller slice of the problem, until the slice is small enough to answer directly. The calls stop at a base case.

The base case gives a plain answer with no more calls. Each call waits for the next one to finish. The answers build back up as the calls return. A missing base case runs until the stack fills.

Recursion fits jobs that split into smaller copies of the same job. A factorial is one such job. A tree walk is another.

The Go Recursion lesson works through a factorial example. The Go Functions lesson covers the function shape it uses.

package main

import "fmt"

func factorial(n int) int {
	if n <= 1 {
		return 1
	}
	return n * factorial(n-1)
}

func main() {
	fmt.Println(factorial(5))
}

Output:
120

18. What is an array, and how is it different from a slice?

An array is a fixed-size group of values of one type. Its length is part of its type. An array with three integers is a different type from an array with four integers.

A slice is a flexible view into an array. It can grow with append. A slice holds a pointer to the underlying array, a length, and a capacity. Two slices can share the same backing array, so changing one can change the other.

Use an array when the size never changes. Use a slice for most lists in real code. The Go Arrays lesson shows fixed-size arrays. The Go Slices lesson builds longer slices the same way.

package main

import "fmt"

func main() {
	arr := [3]int{10, 20, 30}
	slice := []int{10, 20, 30}
	slice = append(slice, 40)
	fmt.Println("array:", arr, "length:", len(arr))
	fmt.Println("slice:", slice, "length:", len(slice))
}

Output:
array: [10 20 30] length: 3
slice: [10 20 30 40] length: 4

19. How do slices work, and what are len and cap?

A slice is a small header with three parts. It points to an underlying array. It stores a length and a capacity.

Len is the number of elements the slice holds now. Cap is the number of elements the backing array can hold before a new array is needed. Appending past the capacity makes Go allocate a bigger array and copy the elements over.

Reslicing changes the length without copying the data. The old elements stay in the backing array. The Go Slices lesson walks through len and cap with short examples. The Go Slices in Depth lesson shows how append and reslicing behave.

package main

import "fmt"

func main() {
	s := make([]int, 2, 5)
	s[0] = 1
	s[1] = 2
	fmt.Println("start:", s, "len:", len(s), "cap:", cap(s))
	s = append(s, 3)
	s = append(s, 4)
	fmt.Println("after append:", s, "len:", len(s), "cap:", cap(s))
	s = s[:2]
	fmt.Println("after reslice:", s, "len:", len(s), "cap:", cap(s))
}

Output:
start: [1 2] len: 2 cap: 5
after append: [1 2 3 4] len: 4 cap: 5
after reslice: [1 2] len: 2 cap: 5

20. How do you sort a slice?

A slice is sorted with the sort package. Sort.Ints sorts integers. Sort.Strings sorts strings. Both sort in place, so the original slice changes.

For a custom order, use sort.Slice with a function that says when one element comes before another. Sort.SliceStable keeps equal elements in their original order. To sort in reverse, wrap the slice with sort.Reverse.

Sorting numbers and strings is the common case. The Go Sorting lesson covers the built-in helpers. The Go Sorting in Depth lesson covers custom ordering.

package main

import (
	"fmt"
	"sort"
)

func main() {
	nums := []int{5, 2, 9, 1, 7}
	sort.Ints(nums)
	fmt.Println("sorted numbers:", nums)
	names := []string{"pear", "apple", "mango"}
	sort.Strings(names)
	fmt.Println("sorted names:", names)
	sort.Sort(sort.Reverse(sort.IntSlice(nums)))
	fmt.Println("reverse numbers:", nums)
}

Output:
sorted numbers: [1 2 5 7 9]
sorted names: [apple mango pear]
reverse numbers: [9 7 5 2 1]

21. What is a map, and how do you use one?

A map is a set of key-value pairs. Each key maps to one value. Keys must be comparable, so strings and integers work well as keys.

Look a value up with a key. The two-value form returns the value and a boolean. The boolean tells whether the key exists. A key that is missing returns the zero value for the value type, so check the boolean when that matters.

Add a pair by assigning to a key. Remove a pair with delete. The Go Maps lesson builds maps from scratch. The Go Maps in Depth lesson covers lookup, deletion, and the two-value form.

package main

import (
	"fmt"
	"sort"
)

func main() {
	scores := map[string]int{"Ada": 90, "Ben": 75, "Cleo": 88}
	scores["Dan"] = 82
	keys := make([]string, 0, len(scores))
	for k := range scores {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		fmt.Println(k, scores[k])
	}
	v, ok := scores["Eve"]
	fmt.Println("Eve found:", ok, "value:", v)
	delete(scores, "Dan")
	fmt.Println("count after delete:", len(scores))
}

Output:
Ada 90
Ben 75
Cleo 88
Dan 82
Eve found: false value: 0
count after delete: 3

22. How do you loop over a slice or a map with range?

Range loops over each element of a slice or a map. For a slice, range gives the index and the value. For a map, range gives the key and the value.

The value is a copy, so changing it does not change the slice or map. Change the element through its index or key instead. Map iteration order is random in Go, so sort the keys first when the output order matters.

Range also works with one variable. With one variable, a slice gives the index and a map gives the key. The Go Range lesson shows both forms. The Go Maps lesson shows range over maps.

package main

import (
	"fmt"
	"sort"
)

func main() {
	fruits := []string{"apple", "banana", "cherry"}
	for i, f := range fruits {
		fmt.Println(i, f)
	}
	ages := map[string]int{"Ada": 30, "Ben": 25}
	keys := make([]string, 0, len(ages))
	for k := range ages {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		fmt.Println(k, ages[k])
	}
}

Output:
0 apple
1 banana
2 cherry
Ada 30
Ben 25

23. What is a struct?

A struct groups related values under one name. Each value is called a field. Fields can have different types. A struct can hold a name string, an age integer, and an active boolean together.

Create a struct value with its fields in order or by name. Field names make the code clear. Access a field with a dot, like book.Title. Change a field the same way.

Structs model real things in a program. A user, a book, and a point are all natural structs. The Go Structs lesson introduces fields and struct values. The Go Structs in Depth lesson covers nesting and copying.

package main

import "fmt"

type Book struct {
	Title  string
	Author string
	Pages  int
}

func main() {
	b := Book{Title: "Dune", Author: "Frank Herbert", Pages: 412}
	fmt.Println(b.Title, "by", b.Author)
	fmt.Println("pages:", b.Pages)
	b.Pages = 500
	fmt.Println("updated pages:", b.Pages)
}

Output:
Dune by Frank Herbert
pages: 412
updated pages: 500

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

A method is a function attached to a type. The receiver is the value the method runs on. It sits between the func keyword and the method name. A method on Rect can compute its area from its own fields.

A value receiver gets a copy of the value. It cannot change the original. A pointer receiver gets the address of the value. It can change the original. Use a pointer receiver for methods that change the value.

Methods keep behaviour with the data it acts on. They make code read like the type does something. The Go Methods lesson introduces receivers with short examples. The Go Methods in Depth lesson covers value and pointer receivers.

package main

import "fmt"

type Rect struct {
	Width  float64
	Height float64
}

func (r Rect) Area() float64 {
	return r.Width * r.Height
}

func (r *Rect) DoubleWidth() {
	r.Width = r.Width * 2
}

func main() {
	r := Rect{Width: 3, Height: 4}
	fmt.Println("area:", r.Area())
	r.DoubleWidth()
	fmt.Println("width after doubling:", r.Width)
	fmt.Println("new area:", r.Area())
}

Output:
area: 12
width after doubling: 6
new area: 24

25. What is a pointer, and when do you need one?

A pointer holds the memory address of a value. The & operator takes the address of a variable. The * operator follows a pointer to the value it points to. A pointer to an integer has the type *int.

Pointers let a function change a value owned by its caller. Pass a pointer when the function must update the value. Pointers also avoid copying large values. A struct passed by value is copied, while a pointer to it is not.

Most Go code uses pointers sparingly. Plain values are the default. Reach for a pointer to share and change state. The Go Pointers lesson shows addresses and dereferencing. The Go Pointers in Depth lesson covers pointers with functions and structs.

package main

import "fmt"

func addOne(n *int) {
	*n = *n + 1
}

func main() {
	x := 10
	p := &x
	fmt.Println("x:", x, "pointer holds address of x")
	*p = 20
	fmt.Println("x after change through pointer:", x)
	addOne(&x)
	fmt.Println("x after addOne:", x)
}

Output:
x: 10 pointer holds address of x
x after change through pointer: 20
x after addOne: 21

26. What is an interface?

An interface lists the methods a type must have. It names behaviour, not data. A type satisfies an interface by having all its methods. There is no keyword to declare that a type implements an interface.

Interfaces let one function accept many types. A function that takes a Speaker can accept any type with a Speak method. The function does not know the concrete type. It only knows the behaviour it needs.

This keeps code flexible. New types work with old functions when they add the right methods. The Go Interfaces lesson introduces the idea with small examples. The Go Interface Composition lesson shows how small interfaces combine into bigger ones.

package main

import "fmt"

type Speaker interface {
	Speak() string
}

type Dog struct{}
type Cat struct{}

func (Dog) Speak() string { return "Woof" }
func (Cat) Speak() string { return "Meow" }

func announce(s Speaker) {
	fmt.Println(s.Speak())
}

func main() {
	announce(Dog{})
	announce(Cat{})
}

Output:
Woof
Meow

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

A type assertion pulls a concrete value out of an interface value. It states the type you expect. The two-value form returns the value and a boolean. The boolean is false when the type does not match. The one-value form panics on a mismatch, so use the two-value form unless you are sure.

A type switch checks an interface value against several types at once. Each case names one type. The code inside a case sees the value as that type. It is a clean way to handle a value that could be one of a few types.

Both tools work with values held as interfaces. They are common in code that handles mixed data. The Go Type Assertions in Depth lesson covers the two-value form. The Go Interfaces lesson shows where interface values come from.

package main

import "fmt"

func describe(v any) {
	switch t := v.(type) {
	case int:
		fmt.Println("int:", t, "doubled:", t*2)
	case string:
		fmt.Println("string:", t, "length:", len(t))
	case bool:
		fmt.Println("bool:", t)
	default:
		fmt.Println("other type")
	}
}

func main() {
	var v any = 42
	n, ok := v.(int)
	fmt.Println("asserted int:", n, "ok:", ok)
	describe(42)
	describe("hello")
	describe(true)
}

Output:
asserted int: 42 ok: true
int: 42 doubled: 84
string: hello length: 5
bool: true

28. What is the empty interface, and what does any mean?

The empty interface has no methods. Every type satisfies it. A variable of that type can hold a value of any type. Any is a newer name for the same type. It reads more clearly in code.

Use any when a function truly accepts any value. A print helper or a mixed list are good cases. The value loses its type information when stored as any. Get it back with a type assertion or a type switch.

Any is flexible, but it hides type errors until the program runs. Prefer a concrete type or a small interface when you know what the value will be. The Go Interfaces lesson introduces the empty interface. The Go Type Assertions in Depth lesson shows how to pull the concrete value back out.

package main

import "fmt"

func main() {
	values := []any{10, "hello", true, 3.5}
	for _, v := range values {
		switch t := v.(type) {
		case int:
			fmt.Println("int:", t)
		case string:
			fmt.Println("string:", t)
		case bool:
			fmt.Println("bool:", t)
		default:
			fmt.Println("other:", t)
		}
	}
	var anything any = "can hold anything"
	fmt.Println(anything)
}

Output:
int: 10
string: hello
bool: true
other: 3.5
can hold anything

29. How does Go handle errors?

Go handles errors as values. A function returns an error alongside its normal result. The error is nil when all went well. The caller checks the error right after the call. This makes error handling visible in the code.

The error type asks for one method, Error, which returns the message as text. The errors package makes simple errors with errors.New. The fmt package makes formatted errors with fmt.Errorf.

Errors are not exceptions. They do not jump up the call stack on their own. The caller decides what to do: return the error, log it, or try something else. The Go Errors lesson shows the return-and-check pattern. The Go The Error Interface lesson shows how the error type works.

package main

import (
	"errors"
	"fmt"
)

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)
	if err != nil {
		fmt.Println("error:", err)
	} else {
		fmt.Println("10 / 2 =", result)
	}
	result, err = divide(10, 0)
	if err != nil {
		fmt.Println("error:", err)
	} else {
		fmt.Println("10 / 0 =", result)
	}
}

Output:
10 / 2 = 5
error: cannot divide by zero

30. What is defer, and when does it run?

Defer schedules a function call to run later. It runs when the surrounding function returns. It runs even when the function returns early. The deferred call waits while the rest of the function runs.

Multiple deferred calls run in reverse order. The last deferred call runs first. This makes defer natural for cleanup. Open a file, defer its close, and the close happens at the end no matter how the function exits.

Defer is common for closing files, unlocking mutexes, and logging how long a function took. The Go Defer in Depth lesson shows the reverse order and cleanup uses.

package main

import "fmt"

func main() {
	defer fmt.Println("deferred: runs last")
	defer fmt.Println("deferred: runs second")
	fmt.Println("main: runs first")
	fmt.Println("main: still running")
}

Output:
main: runs first
main: still running
deferred: runs second
deferred: runs last

31. What is panic, and what does recover do?

Panic stops the normal flow of a function. It unwinds the stack, running deferred functions on the way out. A panic is for a bug or a state the program cannot continue from. It is not a normal way to report an error.

Recover stops a panic. It only works inside a deferred function. Recover returns the value passed to panic. It returns nil when there is no panic. After a recover, the program keeps running from the deferred function.

Use panic for programmer errors, like an out-of-range index. Use errors for problems the caller can handle. The Go Panic and Recover lesson shows the pattern step by step. The Go Errors lesson shows the normal error path to prefer.

package main

import "fmt"

func risky() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("recovered from panic:", r)
		}
	}()
	fmt.Println("about to panic")
	panic("something went wrong")
}

func main() {
	risky()
	fmt.Println("program continues after recovery")
}

Output:
about to panic
recovered from panic: something went wrong
program continues after recovery

32. What is a package, and how do imports work?

A package is a group of related Go files in one directory. Every file in a package declares the same package name. The main package holds the program entry point. Other packages hold reusable code.

Imports bring another package into a file. The import list sits near the top of the file. Code refers to the package by its name, like strings.Join. Go only allows imports that the file actually uses. An unused import is a compile error.

The standard library ships with many packages. Fmt prints text, and strings works with text. Larger programs split code into their own packages. The Go Packages lesson introduces packages and imports. The Go Packages in Depth lesson covers organising a program into packages.

package main

import (
	"fmt"
	"strings"
)

func main() {
	words := []string{"go", "is", "fun"}
	joined := strings.Join(words, " ")
	fmt.Println("joined:", joined)
	fmt.Println("upper:", strings.ToUpper(joined))
	fmt.Println("contains go:", strings.Contains(joined, "go"))
}

Output:
joined: go is fun
upper: GO IS FUN
contains go: true

33. What is a closure?

A closure keeps hold of the variables around it, even after the outer function has finished. It captures those variables. The variables stay alive as long as the closure lives. Each call to the outer function makes fresh captured variables.

A counter is the classic case. The outer function holds a count variable. The returned function adds one to it each time it runs. Two counters made from the same function keep separate counts.

Closures are functions as values. They are passed to other functions and stored in variables. The Go Closures lesson builds a counter step by step. The Go Functions as Values lesson shows closures passed around as values.

package main

import "fmt"

func counter() func() int {
	count := 0
	return func() int {
		count++
		return count
	}
}

func main() {
	next := counter()
	fmt.Println(next())
	fmt.Println(next())
	fmt.Println(next())
	other := counter()
	fmt.Println("new counter:", other())
}

Output:
1
2
3
new counter: 1

34. What are generics, and what is a type parameter?

Generics let one function or type work with many types. A type parameter stands for a type that is chosen later. It is declared in square brackets after the function name. The caller supplies the real type when the function runs.

A first-element function is a good case. Without generics, it needs one copy for integers and one for strings. With a type parameter, one version works for both. Go often infers the type from the argument, so the caller does not write it out.

A constraint limits which types a parameter accepts. The any constraint allows every type. A comparable constraint allows only types that support ==. The Go Generic Functions lesson shows type parameters on functions. The Go Generic Types lesson shows them on structs and other types.

package main

import "fmt"

func first[T any](items []T) T {
	return items[0]
}

func main() {
	fmt.Println("first int:", first([]int{10, 20, 30}))
	fmt.Println("first string:", first([]string{"apple", "banana"}))
	fmt.Println("first bool:", first([]bool{true, false}))
}

Output:
first int: 10
first string: apple
first bool: true

35. What is a goroutine?

A goroutine is a small unit of work that Go runs at the same time as other work. It starts with the go keyword in front of a function call. It costs far less than a full operating system thread.

The main function does not wait for a goroutine on its own. A program can end before the goroutine finishes its work. A sync.WaitGroup gives main a way to wait for the goroutine to finish.

The Go Goroutines lesson shows how to start a goroutine and wait for it. The Go Goroutine Leaks lesson shows what happens when a goroutine never ends.

package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup
	message := ""

	wg.Add(1)
	go func() {
		defer wg.Done()
		message = "hello from a goroutine"
	}()

	wg.Wait()
	fmt.Println(message)
	fmt.Println("main finished")
}

Output:
hello from a goroutine
main finished

36. What is a channel, and what are buffered and unbuffered channels?

A channel is a pipe that moves values between goroutines. One goroutine sends a value into the channel. Another goroutine receives the value from the channel.

An unbuffered channel holds no values. A send waits until a receive is ready. A receive waits until a send is ready.

A buffered channel holds a set number of values. A send waits only when the buffer is full. A receive waits only when the buffer is empty.

The Go Channels in Depth lesson traces more channel patterns. The Go Select lesson shows how to wait on more than one channel at once.

package main

import "fmt"

func main() {
	// Unbuffered channel: the send waits until main receives it.
	unbuffered := make(chan string)
	go func() {
		unbuffered <- "hello"
	}()
	fmt.Println("unbuffered:", <-unbuffered)

	// Buffered channel with capacity 2: two sends fit without a receiver.
	buffered := make(chan int, 2)
	buffered <- 1
	buffered <- 2
	fmt.Println("buffered:", <-buffered, <-buffered)
}

Output:
unbuffered: hello
buffered: 1 2

37. How does select work?

The select statement waits on more than one channel at once. Each case names one channel send or receive. The first case that is ready runs.

A default case runs when every other case is waiting. It keeps select from blocking. It is a common way to check a channel without waiting.

A case can also wait on a timer. That pattern gives a channel operation a time limit. The program moves on when the timer fires first.

The Go Select lesson works through select with channels and timers. The Go Channels in Depth lesson covers the channel basics behind it.

package main

import "fmt"

func main() {
	ready := make(chan string, 1)
	ready <- "ready"

	select {
	case msg := <-ready:
		fmt.Println("received:", msg)
	default:
		fmt.Println("no message")
	}

	empty := make(chan string)
	select {
	case msg := <-empty:
		fmt.Println("received:", msg)
	default:
		fmt.Println("no message yet")
	}
}

Output:
received: ready
no message yet

38. What is a sync.Mutex, and what is a sync.WaitGroup?

A sync.Mutex is a guard that lets one goroutine into shared data at a time. One goroutine locks it before it touches the data. It unlocks it when it is done.

A sync.WaitGroup is a counter that tracks running goroutines. Each goroutine calls Add before it starts. Each one calls Done when it finishes.

The two tools solve different problems. A mutex stops goroutines from changing the same value at the same time. A WaitGroup lets main wait until all the goroutines are done.

The Go Mutex and WaitGroups lesson covers both tools together. The Go Goroutines lesson shows the goroutines they protect.

package main

import (
	"fmt"
	"sync"
)

func main() {
	var mu sync.Mutex
	var wg sync.WaitGroup
	total := 0

	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			mu.Lock()
			total += 10
			mu.Unlock()
		}()
	}

	wg.Wait()
	fmt.Println("total:", total)
}

Output:
total: 50

39. What is a worker pool?

A worker pool is a fixed set of goroutines that share a queue of jobs. Each worker takes one job from the queue. It sends the result back when the job is done.

The pool keeps the number of running goroutines under control. New jobs wait in the queue instead of starting new goroutines. The queue is usually a channel.

A worker pool fits work that splits into many small jobs. Image resizing is one example. Fetching a list of pages is another.

The Go Worker Pools lesson builds a pool step by step. The Go Pipelines lesson shows how pools fit into a longer chain of stages.

package main

import (
	"fmt"
	"sync"
)

type result struct {
	job   int
	value int
}

func worker(jobs <-chan int, results chan<- result, wg *sync.WaitGroup) {
	defer wg.Done()
	for job := range jobs {
		results <- result{job: job, value: job * 2}
	}
}

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

	for w := 0; w < 3; w++ {
		wg.Add(1)
		go worker(jobs, results, &wg)
	}

	go func() {
		for job := 1; job <= 6; job++ {
			jobs <- job
		}
		close(jobs)
	}()

	go func() {
		wg.Wait()
		close(results)
	}()

	ordered := make([]int, 7)
	for r := range results {
		ordered[r.job] = r.value
	}

	for job := 1; job <= 6; job++ {
		fmt.Println("job", job, "->", ordered[job])
	}
}

Output:
job 1 -> 2
job 2 -> 4
job 3 -> 6
job 4 -> 8
job 5 -> 10
job 6 -> 12

40. What is the context package for?

The context package carries deadlines and cancel signals through a program. A function takes a context as its first argument. It stops its work when the context is cancelled.

A context can carry a timeout. The work stops when the time runs out. A context can also be cancelled by hand with its cancel function.

Contexts pass down a chain of function calls. A parent context cancels all of its children. That makes one cancel call stop a whole request.

The Go Context Cancellation lesson shows how to cancel work by hand. The Go Context Deadlines lesson shows how to set a time limit.

package main

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

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	cancel()
	fmt.Println("error:", ctx.Err())
}

Output:
error: context canceled

41. How do you read and write a file in Go?

The os package reads and writes whole files in a few lines. os.WriteFile writes a slice of bytes to a path. os.ReadFile reads the whole file back into a slice of bytes.

Both functions return an error value. A good program checks that error before it uses the result. A missing file or a bad path shows up as an error, not a crash.

Larger files need a different approach. A bufio.Scanner reads a file line by line. An io.Reader streams data in chunks instead of loading it all at once.

The Go File IO lesson covers reading and writing files in detail. The Go IO Interfaces lesson covers readers and writers for larger data.

package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func main() {
	dir, err := os.MkdirTemp("", "go-file")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer os.RemoveAll(dir)

	path := filepath.Join(dir, "note.txt")
	if err := os.WriteFile(path, []byte("hello from a file"), 0644); err != nil {
		fmt.Println("error:", err)
		return
	}

	data, err := os.ReadFile(path)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(string(data))
}

Output:
hello from a file

42. How do you work with JSON in Go?

JSON is a text format for structured data. Go turns a struct into JSON with json.Marshal. It turns JSON back into a struct with json.Unmarshal.

Struct tags control the JSON field names. A tag like `json:"name"` maps a field to a lowercase key. Fields without a tag keep their Go name.

Both functions return an error value. Bad JSON fails at unmarshal time. A type mismatch between the JSON and the struct fails too.

The Go JSON lesson covers marshaling and unmarshaling in detail. The Go Structs in Depth lesson covers the struct tags that shape the output.

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	person := Person{Name: "Ada", Age: 36}

	data, err := json.Marshal(person)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(string(data))

	var decoded Person
	if err := json.Unmarshal(data, &decoded); err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("name:", decoded.Name)
}

Output:
{"name":"Ada","age":36}
name: Ada

43. How do you make an HTTP request, and how do you serve one?

The net/http package handles both sides of HTTP. http.Get sends a GET request to a URL. It returns a response with a status code and a body.

A server starts with http.HandleFunc. It maps a URL path to a handler function. http.ListenAndServe starts the server on a port.

A handler reads the request and writes the response. It writes a status code with WriteHeader. It writes the body with fmt.Fprint.

The Go HTTP Client lesson covers making requests. The Go HTTP Server lesson covers serving them.

package main

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

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "hello from Go")
	}))
	defer server.Close()

	resp, err := http.Get(server.URL)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("status:", resp.StatusCode)
	fmt.Println("body:", string(body))
}

Output:
status: 200
body: hello from Go

44. How do you write a unit test in Go?

A unit test is a function that checks one small piece of code. It lives in a file whose name ends in _test.go. Its name starts with Test and takes a *testing.T value.

A table test holds many cases in a slice. Each case lists inputs and the expected output. A loop runs the function on each case and reports a failure when the result differs.

The go test command runs the tests in a package and reports the failures. It prints PASS for a passing test. It prints FAIL and the file and line for a failing test.

The Go Unit Tests lesson covers the basic test shape. The Go Table Tests lesson covers the table pattern used in the program below.

package main

import "fmt"

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

func main() {
	cases := []struct {
		a, b, want int
	}{
		{1, 2, 3},
		{0, 0, 0},
		{-1, 1, 0},
		{10, 5, 15},
	}

	for _, c := range cases {
		got := add(c.a, c.b)
		if got == c.want {
			fmt.Printf("PASS: add(%d, %d) = %d\n", c.a, c.b, got)
		} else {
			fmt.Printf("FAIL: add(%d, %d) = %d, want %d\n", c.a, c.b, got, c.want)
		}
	}
}

Output:
PASS: add(1, 2) = 3
PASS: add(0, 0) = 0
PASS: add(-1, 1) = 0
PASS: add(10, 5) = 15

45. Coding task: print FizzBuzz from 1 to 15.

Print the numbers from 1 to 15, one per line. Print Fizz for a number divisible by 3. Print Buzz for a number divisible by 5.

Print FizzBuzz for a number divisible by both 3 and 5. The number 15 is the only such number in this range. The both-divisible check must come first, or 15 prints as Fizz.

The remainder operator % tests divisibility. A number is divisible by 3 when n % 3 equals 0. The same test works for 5.

The Go For Loop lesson covers the loop that counts from 1 to 15. The Go If and Else lesson covers the checks inside it.

package main

import "fmt"

func main() {
	for i := 1; i <= 15; i++ {
		switch {
		case i%3 == 0 && i%5 == 0:
			fmt.Println("FizzBuzz")
		case i%3 == 0:
			fmt.Println("Fizz")
		case i%5 == 0:
			fmt.Println("Buzz")
		default:
			fmt.Println(i)
		}
	}
}

Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

46. Coding task: reverse a string.

Reverse a string so its characters run in the opposite order. The word gopher becomes rehpog. The first character becomes the last.

A Go string holds bytes, not characters. Some characters take more than one byte. Converting the string to a slice of runes keeps each character whole.

Two indexes walk toward each other from the ends. Each step swaps the characters at the two indexes. The loop stops when the indexes meet in the middle.

The Go Strings lesson covers runes and string basics. The Go Strings in Depth lesson covers more string work.

package main

import "fmt"

func reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func main() {
	word := "gopher"
	fmt.Println(word, "->", reverse(word))
}

Output:
gopher -> rehpog

47. Coding task: count how many times each word appears.

Count how many times each word appears in a sentence. The sentence here is "go is fun and go is fast". The word go appears twice.

Split the sentence into words first. A map holds one count per word. Each word met raises its tally in the map by one.

Map iteration order is random in Go. Sorting the words before printing keeps the output fixed. The program prints each word with its count in sorted order.

The Go Maps lesson covers maps and counting patterns. The Go Maps in Depth lesson covers more map work.

package main

import (
	"fmt"
	"sort"
	"strings"
)

func main() {
	text := "go is fun and go is fast"
	counts := map[string]int{}
	for _, word := range strings.Fields(text) {
		counts[word]++
	}

	words := make([]string, 0, len(counts))
	for word := range counts {
		words = append(words, word)
	}
	sort.Strings(words)

	for _, word := range words {
		fmt.Println(word, ":", counts[word])
	}
}

Output:
and : 1
fast : 1
fun : 1
go : 2
is : 2

48. Coding task: find the largest number in a slice.

Find the largest number in a slice of numbers. The slice here holds 4, 9, 2, 15, and 7. The answer is 15.

Start with the first number as the largest so far. Walk through the rest of the slice one number at a time. Replace the largest so far whenever a bigger number appears.

The loop checks every number exactly once. The largest so far holds the answer when the loop ends. An empty slice has no largest number, so that case needs a separate check.

The Go Slices lesson covers slice basics. The Go Slice Operations lesson covers more ways to work through a slice.

package main

import "fmt"

func main() {
	numbers := []int{4, 9, 2, 15, 7}
	largest := numbers[0]
	for _, n := range numbers[1:] {
		if n > largest {
			largest = n
		}
	}
	fmt.Println("largest:", largest)
}

Output:
largest: 15

49. Coding task: check whether a word reads the same backwards.

Check whether a word reads the same forwards and backwards. Such a word is called a palindrome. The word level is one, and hello is not.

Compare characters from the two ends. Two indexes walk toward each other from the ends. A mismatch at any step means the word is not a palindrome.

Runes keep multi-byte characters whole during the check. A plain byte comparison can split such a character. The rune version works for words in any language.

The Go Strings lesson covers runes and string basics. The Go For Loop lesson covers the loop that walks the indexes.

package main

import "fmt"

func isPalindrome(word string) bool {
	runes := []rune(word)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		if runes[i] != runes[j] {
			return false
		}
	}
	return true
}

func main() {
	fmt.Println("level:", isPalindrome("level"))
	fmt.Println("hello:", isPalindrome("hello"))
}

Output:
level: true
hello: false

50. Coding task: add up the even numbers in a slice.

Add up only the even numbers in a slice. The slice here holds 1, 2, 3, 4, 5, and 6. The even numbers are 2, 4, and 6, so the answer is 12.

The remainder operator % tests whether a number is even. A number is even when n % 2 equals 0. Odd numbers fail that test and are skipped.

A running total starts at zero. The loop adds each even number to the total. The total holds the answer when the loop ends.

The Go Slices lesson covers slice basics. The Go Range lesson covers the loop that walks the slice.

package main

import "fmt"

func main() {
	numbers := []int{1, 2, 3, 4, 5, 6}
	total := 0
	for _, n := range numbers {
		if n%2 == 0 {
			total += n
		}
	}
	fmt.Println("sum of even numbers:", total)
}

Output:
sum of even numbers: 12

Questions readers ask

How should I pace this sheet over a week?

Cover one group per day, in order. Cover each answer and speak your own first, then read the page version. Type out the programs and run them. Spend the last day on the six coding tasks and on the questions you missed. A short session each day beats one long night before the interview.

Do I need to install Go before I start?

Yes, for the programs. Download Go from go.dev and follow the install steps for your computer. The go version command confirms the install. This sheet was built with Go 1.25.4. Reading the answers works without an install, but running the programs is the part that teaches.

Where do I go after this sheet?

The Go Advanced lessons on reflection, context, and profiling. A small HTTP service of your own, built with the net/http package. The Go Project lessons at the end of each course, which join the ideas into working programs.

Are goroutines the same as threads?

No. A goroutine is a light task managed by the Go runtime, and thousands can run in one program. An operating-system thread is heavier, and a program holds far fewer of them. The runtime maps goroutines onto a small pool of threads. Channels move values between goroutines, so shared memory is rarely needed.