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
- What Are Pointers?
- Pointers and Functions
- Pointer Receivers on Methods
- new() and When to Use Pointers