Using the new vs var in Go

You have a function with an argument, a pointer to a type.

type bar struct{...} func foo(arg *bar) 

Is there a difference between:

 var b bar foo(&b) 

and

 b := new(bar) foo(b) 

Using the new creates distribution.

+8
pointers go
source share
3 answers

No, there is no difference, because, contrary to C, Go explicitly states that you can point to a locally created variable.

From the documentation :

Note that, unlike C, it is normal to return the address of a local variable; memory associated with the variable is saved after the function returns

+10
source share

Both must represent the same pointer to the same object, initialized with the same default value.

spec mentions:

After

 type T struct { i int; f float64; next *T } t := new(T) 

the following is true:

 ti == 0 tf == 0.0 t.next == nil 

The same would be true after

 var t T 

also:

Accepting the address of a composite literal (ยง Address operators ) generates a pointer to a unique instance of the literal.

 var pointer *Point3D = &Point3D{y: 1000} 
+4
source share

In some situations, there are differences. new(T) , as the name implies, returns a, well, a new instance of type T, while var b T is one instance, once and for all (err, actually until the end of its life cycle == goes out of scope , not available...).

Consider this cycle

 var b bar for i := 0; i < 10; i++ { foo(&b) } 

against

 var b *bar for i := 0; i < 10; i++ { b = new(b) foo(b) } 

In the later case, if foo , for example, stores its arg in some container, it leads to 10 instances of bar existing, while the first case has only one - in the variable b .

Another performance difference. The variable b will either be a fully static global variable, or it will usually be at a statically known offset in some function / method call record (a fancy name is usually a stack stack). new OTOH, if not optimized by the compiler, is a memory allocation call. Such a call will cost some non-zero time. If it is made in a loop and is not actually needed, then it can noticeably slow down some code path.

-3
source share

All Articles