# 10 Essential Golang Interview Questions *

## Toptal sourced essential questions that the best Golang developers and engineers can answer. Driven from our community, we encourage experts to submit questions and offer feedback.

Hire a Top Golang Developer Now
is an exclusive network of the top freelance software developers, designers, marketing experts, product managers, project managers, and finance experts in the world. Top companies hire Toptal freelancers for their most important projects.

## Interview Questions

1.

How do you swap two values? Provide a few examples.

Two values are swapped as easy as this:

a, b = b, a


To swap three values, we would write:

a, b, c = b, c, a


The swap operation in Go is guaranteed from side effects. The values to be assigned are guaranteed to be stored in temporary variables before starting the actual assigning, so the order of assignment does not matter. The result of the following operation: a := 1; b := 2; a, b, a = b, a, b is still a = 2 and b = 1, without the risk of changing the value a to the new re-assigned value. This is useful to rely on in many algorithm implementations.

For example, a function that reverses a slice of integers in place:

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

func main() {
a := []int{1, 2, 3}
reverse(a)
fmt.Println(a)
// Output: [3 2 1]
}

2.

How do you copy a slice, a map, and an interface?

You copy a slice by using the built-in copy() function:

a := []int{1, 2}
b := []int{3, 4}
check := a
copy(a, b)
fmt.Println(a, b, check)
// Output: [3 4] [3 4] [3 4]


Here, the check variable is used to hold a reference to the original slice description to make sure it is really copied.

In the next example, on the other hand, operation does not copy the slice contents, only the slice description:

a := []int{1, 2}
b := []int{3, 4}
check := a
a = b
fmt.Println(a, b, check)
// Output: [3 4] [3 4] [1 2]


You copy a map by traversing its keys. Yes, unfortunately, this is the simplest way to copy a map in Go:

a := map[string]bool{"A": true, "B": true}
b := make(map[string]bool)
for key, value := range a {
b[key] = value
}


Following example copies just the description of the map:

a := map[string]bool{"A": true, "B": true}
b := map[string]bool{"C": true, "D": true}
check := a
a = b
fmt.Println(a, b, check)
// Output: map[C:true D:true] map[C:true D:true] map[A:true B:true]


There’s no built-in way in Go to copy an interface. No, the reflect.DeepCopy() function does not exist.

3.

How do you compare two structs? What about two interfaces? Provide examples.

You can compare two structs with the == operator, as you would do with other simple types. Just make sure they do not contain any slices, maps, or functions, in which case the code will not be compiled.

type Foo struct {
A int
B string
C interface{}
}
a := Foo{A: 1, B: "one", C: "two"}
b := Foo{A: 1, B: "one", C: "two"}

println(a == b)
// Output: true

type Bar struct {
A []int
}
a := Bar{A: []int{1}}
b := Bar{A: []int{1}}

println(a == b)
// Output: invalid operation: a == b (struct containing []int cannot be compared)


You can compare two interfaces with the == operator as long as the underlying types are “simple” and identical. Otherwise the code will panic at runtime:

var a interface{}
var b interface{}

a = 10
b = 10
println(a == b)
// Output: true

a = []int{1}
b = []int{2}
println(a == b)
// Output: panic: runtime error: comparing uncomparable type []int


Both structs and interfaces which contain maps, slices (but not functions) can be compared with the reflect.DeepEqual() function:

var a interface{}
var b interface{}

a = []int{1}
b = []int{1}
println(reflect.DeepEqual(a, b))
// Output: true

a = map[string]string{"A": "B"}
b = map[string]string{"A": "B"}
println(reflect.DeepEqual(a, b))
// Output: true

temp := func() {}
a = temp
b = temp
println(reflect.DeepEqual(a, b))
// Output: false


For comparing byte slices, there are nice helper functions in the bytes package: bytes.Equal(), bytes.Compare(), and bytes.EqualFold(). The latter is for comparing text strings disregarding the case, which are much faster than the reflect.DeepEqual().

Apply to Join Toptal's Development Network

and enjoy reliable, steady, remote Freelance Golang Developer Jobs

Apply as a Freelancer
4.

What is wrong with the following code snippet?

type Orange struct {
Quantity int
}

func (o *Orange) Increase(n int) {
o.Quantity += n
}

func (o *Orange) Decrease(n int) {
o.Quantity -= n
}

func (o *Orange) String() string {
return fmt.Sprintf("%v", o.Quantity)
}

func main() {
var orange Orange
orange.Increase(10)
orange.Decrease(5)
fmt.Println(orange)
}


Provide the proper code solution.

This is a trick question because you might think this has something to do with the member variable Quantity being set incorrectly, but actually, it will be set to 5 as expected. The real problem here, which is easy to overlook, is that the String() method that implements the fmt.Stringer() interface will not be invoked when the object orange is being printed with fmt.Println() function, because the method String() is not being defined on a value but only on a pointer:

var orange Orange
orange.Increase(10)
orange.Decrease(5)
fmt.Println(orange)
// Output: {5}

orange := &Orange{}
orange.Increase(10)
orange.Decrease(5)
fmt.Println(orange)
// Output: 5


That is a subtle one, but the fix is simple. You need to redefine the String() method on a value instead of a pointer, and in that case, it will work for both pointers and values:

func (o Orange) String() string {
return fmt.Sprintf("%v", o.Quantity)
}

5.

How would you implement a stack and a queue in Go? Explain and provide code examples.

You use slices to implement a stack or queue by yourself:

type Stack []int
func (s Stack) Empty() bool { return len(s) == 0 }
func (s *Stack) Push(v int) { (*s) = append((*s), v) }
func (s *Stack) Pop() int {
v := (*s)[len(*s)-1]
(*s) = (*s)[:len(*s)-1]
return v
}

type Queue []int
func (q Queue) Empty() bool    { return len(q) == 0 }
func (q *Queue) Enqueue(v int) { (*q) = append((*q), v) }
func (q *Queue) Dequeue() int {
v := (*q)[0]
(*q) = (*q)[1:len(*q)]
return v
}

func main() {
s := Stack{}
s.Push(1)
s.Push(2)
fmt.Println(s.Pop())
fmt.Println(s.Pop())
fmt.Println(s.Empty())
// Output:
// 2
// 1
// true

q := Queue{}
q.Enqueue(1)
q.Enqueue(2)
fmt.Println(q.Dequeue())
fmt.Println(q.Dequeue())
fmt.Println(q.Empty())
// Output:
// 1
// 2
// true
}


The queue implementation above is correct, but it is suboptimal. There are better but lengthier implementations, like this one.

Occasionally, you would prefer the Go standard library’s container/list to implement them for their conciseness, genericity, and extra list data structure related operations:

stack := list.New()
stack.PushBack(1)
stack.PushBack(2)
fmt.Println(stack.Remove(stack.Back()))
fmt.Println(stack.Remove(stack.Back()))
fmt.Println(stack.Len() == 0)
// Output:
// 2
// 1
// true

queue := list.New()
queue.PushBack(1)
queue.PushBack(2)
fmt.Println(queue.Remove(queue.Front()))
fmt.Println(queue.Remove(queue.Front()))
fmt.Println(queue.Len() == 0)
// Output:
// 1
// 2
// true


Although, their usage is generally discouraged for their slower performance, compared to slices iteration pattern. Let’s compare the two following examples:

// Iterate through a list and print its contents.
for e := queue.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}

for _, e := range queue {
fmt.Println(e)
}


“Always use a slice.”, Dave Cheney

Another possibility to implement a queue is to use buffered channels, but this is never a good idea, because:

1. The buffer size is determined at the channel creation and cannot be increased.
2. It is impossible to peek at the next queue element without retrieving it from the queue.
3. There is a risk of deadlock: “Novices are sometimes tempted to use buffered channels within a single goroutine as a queue, lured by their pleasingly simple syntax, but this is a mistake. Channels are deeply connected to goroutine scheduling, and without another goroutine receiving from the channel, a sender—and perhaps the whole program—risks becoming blocked forever. If all you need is a simple queue, make one using a slice.”, Brian Kernighan.
6.

What might be wrong with the following small program?

func main() {
scanner := bufio.NewScanner(strings.NewReader(one
two
three
four
))
var (
text string
n    int
)
for scanner.Scan() {
n++
text += fmt.Sprintf("%d. %s\n", n, scanner.Text())
}
fmt.Print(text)

// Output:
// 1. One
// 2. Two
// 3. Three
// 4. Four
}


The program numbers the lines in a buffer and uses the text/scanner to read the input line-by-line. What might be wrong with it?

First, it is not necessary to collect the input in the string before putting it out to standard output. This example is slightly contrived.

Second, the string text is not modified with the += operator, it is created anew for every line. This is a significant difference between strings and []byte slices — strings in Go are non-modifiable. If you need to modify a string, use a []byte slice.

Here’s a provided small program, written in a better way:

func main() {
scanner := bufio.NewScanner(strings.NewReader(one
two
three
four
))
var (
text []byte
n    int
)
for scanner.Scan() {
n++
text = append(text, fmt.Sprintf("%d. %s\n", n, scanner.Text())...)
}
os.Stdout.Write(text)
// 1. One
// 2. Two
// 3. Three
// 4. Four
}


That is the point of the existence of both bytes and strings packages.

7.

What would you do if you need a hash displayed in a fixed order?

You would need to sort that hash’s keys.

fruits := map[string]int{
"oranges": 100,
"apples":  200,
"bananas": 300,
}

// Put the keys in a slice and sort it.
var keys []string
for key := range fruits {
keys = append(keys, key)
}
sort.Strings(keys)

// Display keys according to the sorted slice.
for _, key := range keys {
fmt.Printf("%s:%v\n", key, fruits[key])
}
// Output:
// apples:200
// bananas:300
// oranges:100

8.

What is the difference, if any, in the following two slice declarations, and which one is more preferable?

var a []int


and

a := []int{}


The first declaration does not allocate memory if the slice is not used, so this declaration method is preferred.

9.

Do you need both GOPATH and GOROOT variables, and why?

Most of the time, you do not need them both. You need only the GOPATH variable set pointing to the Go packages tree or trees.

GOROOT points to the root of the Go language home directory, but it is most probably already set to the directory of the current Go language installation. It is easy to check whether it is so with the go env command:

### Oleksii Asiutin

Freelance Golang Developer
Ukraine
Toptal Member Since September 30, 2016

Oleksii is now working as a DevOps engineer—automating infrastructure management and creating CI/CD pipelines. He has hands-on experience writing server daemons (Node.js, Golang). Previously, he's worked as a full-stack web developer mainly coding with PHP, Python, and so on. As a hobby, Oleksii writes DevOps digests for the Ukrainian Software Developer Community and helps people who have a passion for software programming.

### Rahul Agrawal

Freelance Golang Developer
India
Toptal Member Since April 5, 2018

Rahul has more than ten years of software development experience, which includes co-founding AxisRooms.com (used by 20,000+ hotels). He has worked extensively across the stack, and his areas of expertise include Golang, Java, Python, Android, React, React Native, and Angular.