Go Reference ยท Built-in Functions
Go new() function
Reference for Go new(): allocate a zero value of any type and get a pointer to it, how it differs from make() and &T{}, and when it is worth using.
new(T) allocates a variable of type T, sets it to the zero value of T, and returns a pointer of type *T to it. It works with any type, including int, string, structs and arrays.
In practice new is used less than &T{} for structs, because the composite literal can set fields at the same time. Its main use is to get a pointer to a zero value of a basic type, and to keep code short when you need a fresh *int or a *bytes.Buffer.
p := new(int) *p = 42 fmt.Println(*p) // 42
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func new(T Type) *T
| Name | Description |
|---|---|
T |
Any type. This is the one built-in that takes a type, not a value, as its argument. |
Returns: a non-nil pointer to a new variable holding the zero value of T.
Edge cases: new cannot set an initial value. Since Go 1.26 the argument may also be an expression, as in new(42) or new(time.Now()), which allocates a variable initialized to that value; the version in your go.mod must allow it. On older versions use a helper function or a temporary variable.
Usage notes
- Zero values are the point.
new(T)is equivalent to declaringvar x Tand taking&x. Because Go zero values are often useful (an emptysync.Mutex, abytes.Buffer),newgives a ready-to-use object. - Prefer
&T{...}for structs when you want to set fields:&Config{Port: 8080}. newis notmake.new([]int)is a pointer to anilslice, andnew(map[K]V)a pointer to anilmap you cannot write to. Usemake()for slices, maps and channels.- Pointers to basic values are needed for optional fields (
*intin JSON structs, for example).p := new(int)is the simplest way to create one. - No cleanup needed. The variable lives as long as something refers to it; whether it sits on the stack or heap is decided by escape analysis, not by
new. - Returning the address of a local variable is safe in Go; the compiler moves it to the heap when needed.
Related
make(), Pointers,& and *, Zero values- Lessons: make and new, Pointers