Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocation: new(Foo) vs Foo{}

Tags:

go

What is the difference between the following syntaxes for creating an object? Why 2 different methods if result is the same?

type Foo struct {
    X int
}

f1 := &Foo{}
f2 := new(Foo)
like image 934
ivanzoid Avatar asked Jul 28 '14 13:07

ivanzoid


1 Answers

Using new is the only way to directly return a pointer of a native type (int, float64, uint32, ...) without creating a normal variable first then returning a pointer to it.

There's a longer discussion about it on https://groups.google.com/forum/#!topic/golang-nuts/K3Ys8qpml2Y and https://groups.google.com/forum/#!topic/golang-nuts/GDXFDJgKKSs, but basically it's useless.

Quote by Dave Cheney:

new isn't going away, it can't, it's part of the guaranteed specification for Go 1.

You don't need to use it, most people don't, but that doesn't mean it doesn't have a use.

like image 66
OneOfOne Avatar answered Oct 06 '22 20:10

OneOfOne