← Back to Go Course | Chapter 8: Pointers | Lesson 5 of 6

The new() Function

new() is a quick way to say 'give me an empty box for this type, already zeroed out, and hand me its address'.

Using new() for a Basic Type

new(T) allocates memory for a value of type T, zeroes it, and returns a pointer to it (*T) -- useful when you need a pointer to a fresh zero value without an existing variable to take the address of.

Example: Using new() for a Basic Type

markup
package main

import "fmt"

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

new() with a Struct

new(Struct) returns a pointer to a zero-valued struct, functionally similar to &Struct{} but without the option to set any initial field values inline.

Note: &Type{Field: value} is usually preferred since it lets you set fields in the same expression.

Example: new() with a Struct

markup
package main

import "fmt"

type Point struct {
	X, Y int
}

func main() {
	p := new(Point)
	p.X = 5
	p.Y = 10
	fmt.Println(p)
}

new() vs make()

new() and make() are easy to confuse: new(T) works for any type and returns a pointer to zeroed memory, while make() only works on slices, maps, and channels, and returns an initialized (not zeroed-and-pointed-to) value of that type itself, not a pointer.

Example: new() vs make()

markup
package main

import "fmt"

func main() {
	p := new([]int)   // *[]int pointing to a nil slice
	s := make([]int, 3) // []int, ready to use with length 3
	fmt.Println(*p, s)
}
Common Mistakes
  1. Confusing new(T), which returns a *T pointing at a zeroed T, with make(), which is only for slices/maps/channels and doesn't return a pointer.
  2. Using new() out of habit for structs when a struct literal with &Type{} is more idiomatic and lets you set initial fields.
  3. Expecting new() to run any custom initialization logic -- it purely zeroes memory, nothing more.
Chapter Summary
  • new(T) allocates zeroed memory for a T and returns a *T pointing at it.
  • new() works for any type, but is most commonly seen with basic types or simple structs.
  • &Type{} is generally preferred over new(Type) for structs, since it allows setting initial field values.
  • make() is a different builtin, reserved specifically for slices, maps, and channels.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.