0Pricing
Go Academy · Lesson

new() and When to Use Pointers

Allocation with new and common pointer patterns

new() and When to Use Pointers is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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)
}

When to Return a Pointer

Return a pointer from a constructor when:

  • The struct is stateful and callers must share the same instance
  • The struct has pointer-receiver methods (needed for interface satisfaction)
  • The struct is large and copies would be expensive

When to Return a Value

Return a value when:

  • The type is small (a few fields)
  • It's immutable configuration
  • You want to make it clear callers get independent copies

Example: time.Time is returned by value despite having many methods.

Pointers in Slices and Maps

Storing pointers in collections allows mutations to be shared:

package main
import "fmt"

type User struct{ Name string; Score int }

func main() {
    users := []*User{{"Alice", 0}, {"Bob", 0}}
    users[0].Score = 100
    fmt.Println(users[0]) // &{Alice 100}
}

Pointer to Primitive for Optionality

A *int or *string field can be nil to mean "not set", which is useful for JSON with omitempty or optional DB columns:

package main
import "fmt"

type Profile struct {
    Name string
    Age  *int // nil means not provided
}

func main() {
    p := Profile{Name: "Alice"}
    fmt.Println(p.Age == nil) // true
    age := 30
    p.Age = &age
    fmt.Println(*p.Age) // 30
}

Avoiding Pointer Proliferation

Excessive pointer use increases GC pressure and reduces cache locality. Benchmark before switching value types to pointers purely for performance.

make vs new

make initializes slices, maps, and channels (they need internal setup). new zero-allocates any type and returns a pointer. They serve different purposes:

package main
import "fmt"

func main() {
    s := make([]int, 5)           // usable slice
    m := make(map[string]int)     // usable map
    p := new(int)                 // *int pointing to 0
    fmt.Println(s, m, *p)
}

Immutable Pointer Pattern

Return *T but document it as immutable; consumers should not modify it. This is common in config objects shared across goroutines.

Pointer Safety Summary

Rules to stay safe with pointers:

  • Always check nil before dereferencing
  • Don't store pointers to stack variables longer than the variable's lifetime (Go's escape analysis handles this)
  • Never cast unsafe.Pointer unless absolutely necessary
  • Let the compiler manage stack vs heap

Quick Check

What does new(int) return?

Recap: new and Pointers

Key takeaways:

  • new(T) returns *T zeroed — rarely used; prefer &T{}
  • Return values when small/immutable; pointers when stateful/large
  • *T fields enable nil-as-absent semantics
  • Don't overuse pointers — GC has a cost

Practice Prompt

Create a Settings struct with a *int field for MaxConnections. Write a function that accepts *Settings and sets a default value only when the field is nil.

Frequently asked questions

Is the “new() and When to Use Pointers” lesson free?

Yes — the full text of “new() and When to Use Pointers” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “new() and When to Use Pointers”?

Allocation with new and common pointer patterns You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “new() and When to Use Pointers” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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