New Versus Make For Slices Maps Channels

new(T) allocates a zeroed value and returns a pointer to any type, while make builds ready-to-use slices, maps, and channels only.

GoData Integrity

Code

gosnippet
23 lines
package main

import "fmt"

func main() {
	// new(T): allocates zeroed storage and returns a pointer; works for any type
	counter := new(int)
	fmt.Println("new(int) dereferenced:", *counter)

	// make: only for slices, maps, and channels; returns an initialized value ready for writes
	items := make([]string, 0, 4)
	users := make(map[string]int)
	updates := make(chan int, 2)

	items = append(items, "a")
	users["ada"] = 1
	updates <- 7
	fmt.Println("slice:", items, "map:", users, "chan len:", len(updates))

	// new(map[string]int) yields a pointer to a nil map: make it first before writing
	ptr := new(map[string]int)
	fmt.Println("new(map) inner is nil:", *ptr == nil)
}

What the code does

The working parts are the function main.

Points of care

  • Nothing to install: every API here comes with the runtime itself.

Applying it

The main signature is written as func main()

Look for the new(int) dereferenced:, slice:, new(map) inner is nil: prefixes as the file executes; they connect every printed line to the step behind it.

Statements that decide the outcome

items := make([]string, 0, 4)
users := make(map[string]int)
updates := make(chan int, 2)

Interactive Tools for This Topic

FAQ

What does New Versus Make For Slices Maps Channels print when run?
Execute the whole file; each printed line is prefixed with a label like `new(int) dereferenced:`, `slice:`, `new(map) inner is nil:`.