Interview Question: What is the difference between new() and make() in Golang?

Publish date: 2025-02-22
Tags: Go, Interview-Questions

Key Takeaways

What is the difference between new and make in Golang

Why Understanding new() and make() Matters in Go

In Go, memory management is handled differently compared to languages like C or Java. Misusing new() or make() can lead to runtime errors such as nil pointer dereferences or uninitialized data structures. Knowing the difference between these two functions is a common topic in software engineering interviews.

This guide will explain everything you need to know about new() and make() in Go, including their differences, use cases, and common mistakes to avoid.

What Does new() Do?

The new() function in Go allocates memory for a given type and returns a pointer to it. The allocated memory is initialized to the type’s zero value (e.g., 0 for integers, "" for strings, false for booleans).

Syntax

pointer := new(Type) // Returns *Type

Example

// Allocating a pointer to an int
numPtr := new(int)
fmt.Println(*numPtr) // Output: 0 (zero value of int)

// Allocating a pointer to a struct
type Person struct { Name string; Age int }
personPtr := new(Person)
fmt.Println(personPtr) // Output: &{ 0 }

When to Use new()

What Does make() Do?

The make() function in Go is used to initialize slices, maps, and channels so they are ready to use. Unlike new(), make() returns the actual value (not a pointer).

Syntax

slice := make([]Type, length, capacity)  
m := make(map[KeyType]ValueType)  
ch := make(chan Type)

Example

// Slice with length 3
names := make([]string, 3)
names[0] = "Alice" // Works (initialized)
fmt.Println(names) // Output: [Alice  ]

// Map
scores := make(map[string]int)
scores["Bob"] = 85 // No error

When to Use make()

new() vs make(): Key Differences

Here’s a table summarizing the key differences between new() and make():

Feature new() make()
Returns Pointer (*Type) Initialized value (Type)
Used For Any type (int, struct, etc.) Only slices, maps, channels
Initializes Zero value (0, “”, false) Ready-to-use structure

Memory Management

Go simplifies memory management by handling it automatically:

Conclusion

Understanding the differences between new() and make() is essential for writing effective Go code. Using these functions correctly will help you allocate memory properly, initialize data structures, and create efficient, idiomatic Go programs. With this knowledge, you will be well-prepared for your software engineering interview.

Tags: Go, Interview-Questions