ProgramGuru

The new() Function

Start with The new() Function

The built-in new function allocates a zero-initialized value and returns a pointer to it.

What you’ll learn

  • Explain the main purpose of the new() function.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

new(int) has type *int, and the target begins as 0. You can change it with *p = 12. The expression &T{...} is often a readable alternative for struct values initialized with fields.

new does not initialize a map’s internal storage or a slice’s backing array. For those collection types, make often provides the immediately usable value you need.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for newnew returns a pointer to zero-initialized storage.new(int)Step 1Pointer to int=0Step 2*p = 12Step 3Read 12Step 4new returns a pointer to zero-initialized storage.
new returns a pointer to zero-initialized storage.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	number := new(int)
	fmt.Println("Zero:", *number)
	*number = 12
	fmt.Println("Updated:", *number)
	fmt.Println("Non-nil:", number != nil)
}

Output

Zero: 0
Updated: 12
Non-nil: true

Trace what the program does

new(int) returns a non-nil pointer to a zero-valued integer. Reading yields 0; the assignment updates the allocated integer to 12.

Avoid common mistakes

  • new(map[string]int) produces a pointer to a nil map, not an initialized writable map.
  • Calling new does not necessarily force allocation on the heap; the compiler can optimize storage placement.

Try it yourself

Use new(bool), check its zero value, and then change it through the pointer.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What is the type of new(int)?
Choose one answer. You can try again.

Answer and explanation

*int

Correct. new(int) returns a non-nil pointer to a zero-valued integer.

What you should remember

You have practiced The new() Function in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: The make() Function →