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.
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: trueTrace 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 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.