DeployU
Interviews / Backend Engineering / What is the difference between `make` and `new` in Go?

What is the difference between `make` and `new` 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 create a new map. You are not sure whether to use make or new to create the map.

The Challenge

Explain the difference between make and new in Go. When would you use one over the other?

Wrong Approach

A junior engineer might think that they are interchangeable. They might not be aware of the difference in what they return or the types of objects that they can be used to create.

Right Approach

A senior engineer would be able to provide a detailed explanation of the differences between `make` and `new`. 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

Featurenewmake
PurposeTo allocate memory for a new object and return a pointer to it.To initialize and allocate memory for slices, maps, and channels.
Return ValueA pointer to the new object.The new object itself (not a pointer).
Use CasesWhen you need a pointer to a new object.When you need to create a slice, map, or channel.

Step 2: Choose the Right Tool for the Job

For our use case, we should use make. This is because we are creating a map, and make is the correct tool for creating slices, maps, and channels.

Step 3: Code Examples

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

new:

package main

import "fmt"

func main() {
    p := new(int)
    fmt.Println(*p) // 0
}

make:

package main

import "fmt"

func main() {
    m := make(map[string]int)
    m["a"] = 1
    fmt.Println(m["a"]) // 1
}

Practice Question

You want to create a new slice with a capacity of 10. Which of the following would you use?