DeployU
Interviews / Backend Engineering / What is the difference between a pointer and a value in Go?

What is the difference between a pointer and a value in Go?

conceptual Core Concepts Interactive Quiz Code Examples

The Scenario

You are a backend engineer at a fintech company. You are writing a new service that needs to pass a large data structure to a function. You are not sure whether to pass the data structure by value or by pointer.

The Challenge

Explain the difference between passing a data structure by value and by pointer in Go. What are the pros and cons of each approach, and which one would you choose for this use case?

Wrong Approach

A junior engineer might not be aware of the difference between pointers and values. They might just choose one at random, without considering the performance and memory implications of their choice.

Right Approach

A senior engineer would be able to provide a detailed explanation of the differences between pointers and values. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in this use case.

Step 1: Understand the Key Differences

FeaturePass by ValuePass by Pointer
CopyingA copy of the data structure is created and passed to the function.A pointer to the data structure is passed to the function.
MutabilityIf you modify the data structure in the function, it will not be modified in the caller.If you modify the data structure in the function, it will be modified in the caller.
PerformanceCan be slow for large data structures, due to the cost of copying the data.Faster than pass by value for large data structures.

Step 2: Choose the Right Tool for the Job

For our use case, we should pass the data structure by pointer. This is because the data structure is large, and we want to avoid the cost of copying it.

Step 3: Code Examples

Here are some code examples that show the difference between the two approaches:

Pass by Value:

package main

import "fmt"

func main() {
    x := 1
    increment(x)
    fmt.Println(x) // 1
}

func increment(x int) {
    x++
}

Pass by Pointer:

package main

import "fmt"

func main() {
    x := 1
    increment(&x)
    fmt.Println(x) // 2
}

func increment(x *int) {
    *x++
}

Practice Question

You are writing a function that needs to modify a large data structure. Which of the following would be the most appropriate?