Go Skills

Make VS New

New

The new built-in function allocates memory.

The first argument is a type, not a value, and the value returned is a pointer to a newly allocated zero value of that type.

  • Returns pointer
  • initialises to zero value of the type
  • used for all types
package main

import "fmt"

type Person struct {
	Name  string
	Age   int
}

func main() {
	personPtr := new(Person)
	personPtr.Name = "John Doe"
	personPtr.Age = 30

	fmt.Println(personPtr)

// Creating a pointer to a float64:
   floatPtr := new(float64)
	*floatPtr = 3.14

	fmt.Println(*floatPtr)

// Creating a pointer to a slice:
   slicePtr := new([]int)
	*slicePtr = make([]int, 5)

	fmt.Println(*slicePtr)

// Creating a pointer to an integer:
   intPtr := new(int)
	*intPtr = 42

	fmt.Println(*intPtr)
}

Make

The make built-in function allocates and initialises an object of type slice, map, or chan (only).

Like new, the first argument is a type, not a value.

Unlike new, make’s return type is the same as the type of its argument, not a pointer to it.

  • Returns an initialised value of type T
  • Does not initialise to zero value of the type
  • Used for only slices, maps and channels

Used for only slices, maps and channels

// Creating a slice:
slice := make([]int, 5, 10)

// Creating a map:
studentAges := make(map[string]int)

// Creating a channel:
dataChannel := make(chan string)

// Creating a buffered channel:
bufferedChannel := make(chan int, 10)