Use of 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 any difference between:

var b bar


b := new(bar)

The use of new creates an allocation.


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

From the documentation :

Note that, unlike in C, it’s perfectly OK to return the address of a
local variable; the storage associated with the variable survives
after the function returns

Answered By – Denys Séguret

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.