0Pricing
Go Academy · Lesson

new() and When to Use Pointers

Allocation with new and common pointer patterns

The new() Built-in

new(T) allocates a zeroed T and returns a *T. It's equivalent to &T{} for structs:

package main
import "fmt"

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

    type Point struct{ X, Y int }
    pt := new(Point)
    fmt.Println(*pt)    // {0 0}
}

new vs &T{}

For structs, &T{} is more idiomatic and allows field initialization. new is rarely used in modern Go:

package main
import "fmt"

type Config struct{ Port int; Host string }

func main() {
    a := new(Config)          // zeroed
    b := &Config{Port: 8080}  // initialized
    fmt.Println(a, b)
}

All lessons in this course

  1. What Are Pointers?
  2. Pointers and Functions
  3. Pointer Receivers on Methods
  4. new() and When to Use Pointers
← Back to Go Academy