The new() Function
In this page:
Using new() for a Basic Type
new(T) allocates memory for a value of type T, zeroes it, and returns a pointer to it (*T) -- useful when you need a pointer to a fresh zero value without an existing variable to take the address of.
Example: Using new() for a Basic Type
package main
import "fmt"
func main() {
p := new(int)
fmt.Println(*p) // zero value: 0
*p = 42
fmt.Println(*p)
}
Login to try C/C++/Java/PHP code in the editor
new() with a Struct
new(Struct) returns a pointer to a zero-valued struct, functionally similar to &Struct{} but without the option to set any initial field values inline.
Note: &Type{Field: value} is usually preferred since it lets you set fields in the same expression.
Example: new() with a Struct
package main
import "fmt"
type Point struct {
X, Y int
}
func main() {
p := new(Point)
p.X = 5
p.Y = 10
fmt.Println(p)
}
Login to try C/C++/Java/PHP code in the editor
new() vs make()
new() and make() are easy to confuse: new(T) works for any type and returns a pointer to zeroed memory, while make() only works on slices, maps, and channels, and returns an initialized (not zeroed-and-pointed-to) value of that type itself, not a pointer.
Example: new() vs make()
package main
import "fmt"
func main() {
p := new([]int) // *[]int pointing to a nil slice
s := make([]int, 3) // []int, ready to use with length 3
fmt.Println(*p, s)
}
Login to try C/C++/Java/PHP code in the editor
- Confusing new(T), which returns a *T pointing at a zeroed T, with make(), which is only for slices/maps/channels and doesn't return a pointer.
- Using new() out of habit for structs when a struct literal with &Type{} is more idiomatic and lets you set initial fields.
- Expecting new() to run any custom initialization logic -- it purely zeroes memory, nothing more.
- new(T) allocates zeroed memory for a T and returns a *T pointing at it.
- new() works for any type, but is most commonly seen with basic types or simple structs.
- &Type{} is generally preferred over new(Type) for structs, since it allows setting initial field values.
- make() is a different builtin, reserved specifically for slices, maps, and channels.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: