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 NowTwo 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]
}
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.
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()
.
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)
}
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:
- The buffer size is determined at the channel creation and cannot be increased.
- It is impossible to peek at the next queue element without retrieving it from the queue.
- 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.
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.
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
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:
$ go env
…
GOROOT=“/home/zabb/go”
…
It is necessary to set the GOROOT
variable if there are multiple Go language versions on the same system or if the Go language has been downloaded as a binary package taken from the internet or transferred from another system.
Why would you prefer to use an empty struct{}
? Provide some examples of the good use of the empty struct{}
.
You would use an empty struct when you would want to save some memory. Empty structs do not take any memory for its value.
a := struct{}{}
println(unsafe.Sizeof(a))
// Output: 0
This saving is usually insignificant and is dependent on the size of the slice or a map. Although, more important use of an empty struct is to show a reader you do not need a value at all. Its purpose in most cases is mainly informational. Here are a few examples where it can be useful:
- When implementing a data set:
set := make(map[string]struct{})
for _, value := range []string{"apple", "orange", "apple"} {
set[value] = struct{}{}
}
fmt.Println(set)
// Output: map[orange:{} apple:{}]
- With the
seen
hash, like when traversing a graph:
seen := make(map[string]struct{})
for _, ok := seen[v]; !ok {
// First time visiting a vertex.
seen[v] = struct{}{}
}
- When building an object, and only being interested in a grouping of methods and no intermediary data, or when you do not plan to retain the object state. In the example below it does not make a difference whether the method is called on the same (case #1) or on two different objects (case #2):
type Lamp struct{}
func (l Lamp) On() {
println("On")
}
func (l Lamp) Off() {
println("Off")
}
func main() {
// Case #1.
var lamp Lamp
lamp.On()
lamp.Off()
// Output:
// on
// off
// Case #2.
Lamp{}.On()
Lamp{}.Off()
// Output:
// on
// off
}
- When you need a channel to signal an event, but do not really need to send any data. This event is also not the last one in the sequence, in which case you would use the
close(ch)
built-in function.
func worker(ch chan struct{}) {
// Receive a message from the main program.
<-ch
println("roger")
// Send a message to the main program.
close(ch)
}
func main() {
ch := make(chan struct{})
go worker(ch)
// Send a message to a worker.
ch <- struct{}{}
// Receive a message from the worker.
<-ch
println(“roger")
// Output:
// roger
// roger
}
These sample questions are intended as a starting point for your interview process. If you need additional help, explore our hiring resources—or let Toptal find the best developers, designers, marketing experts, product managers, project managers, and finance experts for you.
Submit an interview question
Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.
Looking for Golang Developers?
Looking for Golang Developers? Check out Toptal’s Golang developers.
Kleber Pinel Bernardo da Silva
Kleber has over 17 years of successful programming experience and as an engineer manager. He is most proficient in Go and Ruby on Rails, but he enjoys mastering new technologies to solve a broader range of problems efficiently. He has thrived both as a group leader and in individual settings.
Show MoreMarcelo Ignacio Aguilera
Marcelo is a senior full-stack developer with 8+ years of experience specializing in building microservice-based back ends for large eCommerce platforms and job-seeking sites. He has integrated blockchain into back-end systems using Go and Node.js. Always open to new challenges, Marcelo also thrives in user-friendly front-end development.
Show MoreJhonattan Manrique
Jhonattan is a dynamic developer with a solid track record of 13 years in the industry. He enjoys software design, programming languages, and tackling complex problems, gaining extensive experience with various programming tools and technologies. Jhonattan's expertise includes Go, C#, Rust, distributed systems, microservices, streaming data tools, and cloud platforms like AWS, GCP, and DigitalOcean.
Show MoreToptal Connects the Top 3% of Freelance Talent All Over The World.
Join the Toptal community.