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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With