Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 147 ยท Pointers and Memory

new, make and Composite Literals

Understand the difference between new and make in Go, how composite literals and &T{} create values, why zero values are useful, and how NewX constructor functions fit in.

Go gives you several ways to bring a value into existence: a plain var declaration, a composite literal like Point{1, 2}, the built-in new, the built-in make, and your own constructor functions. Beginners often ask which to use, and in particular what the difference between new and make is.

The short answer: new(T) gives you a pointer to a zeroed T for any type; make is only for slices, maps and channels, and returns a ready-to-use value (not a pointer); and composite literals are what you will write most of the time. This lesson explains each, shows the traps (the nil map above all), and ends with the idioms for initialization and NewX functions. It assumes you have read Pointers.

Zero values come first

In Go, a variable that is declared but not given a value is never garbage. It holds the zero value of its type: 0 for numbers, "" for strings, false for booleans, and nil for pointers, slices, maps, channels, functions and interfaces. Structs and arrays are zeroed field by field.

Go Everything starts zeroed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Good Go types are designed so the zero value is ready to use whenever possible. A sync.Mutex is unlocked, a bytes.Buffer is an empty buffer, and a nil slice works with append and len. When you can, design your own types the same way, and you will need fewer constructors.

Composite literals

A composite literal creates a struct, array, slice or map and sets its contents in one expression.

Go Composite literals for every kind of type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Prefer named fields for structs with more than two or three fields. Positional literals break when someone adds a field, and the compiler (and go vet) will warn you about unkeyed fields of structs from other packages.

&T{} creates a pointer

Putting & in front of a composite literal allocates the value and gives you a pointer to it. This is the most common way to create a pointer to a struct:

Go &T{} versus T{}

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

new

new(T) allocates a zeroed variable of type T and returns a *T. It works for any type. With composite literals available, new is mostly used for non-struct types, where there is no literal to take the address of:

Go new for non-struct types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The new(expr) form was added in Go 1.26; see Pointers for details. Writing new([]int) is almost always a mistake, which leads us to make.

make

make is a built-in for exactly three kinds of types: slices, maps and channels. These types need internal setup (a backing array, a hash table, a queue) that a plain zero value does not have. make performs that setup and returns an initialized value of the same type, not a pointer.

Call Result
make([]T, length) slice of length zero elements, capacity length
make([]T, length, capacity) slice with extra room to grow
make(map[K]V) or make(map[K]V, hint) empty map, optional size hint
make(chan T) or make(chan T, size) unbuffered or buffered channel
Go make for slices, maps and channels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The two-argument form make([]int, 3) creates three elements. A very common mistake is make([]int, 5) followed by append, which adds the new elements after five zeros. If you want to fill a slice by appending, use make([]int, 0, 5).

new versus make, and the nil map

Here is the difference in one place. new hands back a pointer to a zero value, and for a map the zero value is nil, which you cannot write to.

Go Writing to a nil map (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The program prints true 0 0 and then dies with panic: assignment to entry in nil map. Reading from, ranging over, and taking the length of a nil map are all fine. Only writing is not. The fix is to initialize it with make or a literal:

Go Fixing the nil map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Nil slices are friendlier: append works on them, so var s []int followed by s = append(s, 1) is idiomatic. Only maps (and channels, where a nil channel blocks forever) need explicit initialization before use.

Constructor functions

Go has no constructors in the language. The convention is a plain function named NewT (or just New when the package's main type is T) that returns a ready-to-use value, usually a pointer. A constructor is worth writing when the zero value is not useful, for example when a struct holds a map that must be initialized, or when you need to validate arguments.

Go A NewX constructor that initializes a map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The second half shows why the constructor matters: calling Add on a zero Registry hits the nil map. An alternative that keeps the zero value usable is to create the map lazily inside Add:

Go
func (r *Registry) Add(name string, n int) {
	if r.items == nil {
		r.items = make(map[string]int)
	}
	r.items[name] += n
}

Choose whichever suits the type. The standard library uses both styles. Constructors, Options and Builders goes much deeper into validation and the functional options pattern.

Initialization patterns

A few idioms you will see everywhere:

  • Declare, then fill: var buf strings.Builder and use it directly, relying on a useful zero value.
  • Allocate with capacity when you know the size: out := make([]string, 0, len(in)) avoids repeated reallocation in a loop.
  • Pointer from literal: cfg := &Config{Timeout: 5 * time.Second}.
  • Return early with zero values: on an error, return nil or the type's zero value rather than a half-built object.
  • Package-level maps and slices are initialized with literals: var weekdays = []string{"Mon", "Tue"}.
Go Preallocating with make

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

If you feel unsure what to write, ask: is it a slice, map or channel? Use make (or a literal). Is it a struct? Use a composite literal, with & if you need a pointer. Anything else that needs a pointer? Use new.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which built-in must you use (or replace with a literal) before writing to a map?

    make(map[K]V) allocates the map. A map literal also works. A nil map panics on write.
  2. 2. What does make([]int, 3) followed by append(s, 7) produce?

    make creates three zero elements first. append adds after them, giving [0 0 0 7].
  3. 3. What is the type of new(float64)?

    new(T) always returns *T, a pointer to a freshly allocated, zeroed T.
  4. 4. What do new(Server) and &Server{} have in common?

    They are equivalent. &Server{} is more common because it lets you set fields in the same expression.
  5. 5. What does this print? var s []int; s = append(s, 1); fmt.Println(s, s == nil)

    append works on a nil slice and returns a new non-nil slice, so the output is [1] false.

Summary

  • Every variable starts at its type's zero value; design your own types so the zero value is useful.
  • Composite literals (Point{1, 2}, []int{1, 2}, map[string]int{}) are the everyday way to create values; &T{} gives a pointer.
  • new(T) returns a *T to a zeroed value; since Go 1.26 new(expr) initializes it as well.
  • make is only for slices, maps and channels, and returns the value itself (never a pointer).
  • A nil map can be read but not written; initialize with make or a literal. A nil slice works with append.
  • Use NewX functions when the zero value is not usable or arguments need validation. Preallocate with make([]T, 0, n) when the size is known.

Next: Stack, Heap and Escape Analysis