64

In Go, is there a notable difference between the following two segments of code:

v := &Vector{}

as opposed to

v := new(Vector)
Lincoln Bergeson
  • 3,301
  • 5
  • 36
  • 53
  • 2
    possible duplicate of [Go: why would I make() or new()?](http://stackoverflow.com/questions/9320862/go-why-would-i-make-or-new) – Dave Cheney Aug 17 '14 at 08:40

3 Answers3

54

No. What they return is the same,

package main

import "fmt"
import "reflect"

type Vector struct {
    x   int
    y   int
}

func main() {
    v := &Vector{}
    x := new(Vector)
    fmt.Println(reflect.TypeOf(v))
    fmt.Println(reflect.TypeOf(x))
}

Result:

*main.Vector
*main.Vector

There is some contention on the mailing list that having both is confusing:

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/GDXFDJgKKSs

One thing to note:

new() is the only way to get a pointer to an unnamed integer or other basic type. You can write "p := new(int)" but you can't write "p := &int{0}". Other than that, it's a matter of preference.

Source : https://groups.google.com/d/msg/golang-nuts/793ZF_yeqbk/-zyUAPT-e4IJ

minikomi
  • 8,363
  • 3
  • 44
  • 51
25

Yes, there is a fundamental difference between the two code fragments.

v := &Vector{}

Works only for Vector being a struct type, map type, array type or a slice type

v := new(Vector)

Works for Vector of any type.

Example: http://play.golang.org/p/nAHjL1ZEuu

zzzz
  • 87,403
  • 16
  • 175
  • 139
  • Saying `new(Map)` isn't a good idea though: http://play.golang.org/p/u89EYchY5n - maps, slices and channels must be made with `make()`, and since they are reference types anyway making them with `new()` is pointless. – Nick Craig-Wood Nov 08 '12 at 09:07
  • That's not a problem of `new`. Actually there's nothing wrong with `new(anyType)`: http://play.golang.org/p/e3hmtK_IV8 – zzzz Nov 08 '12 at 09:39
  • You are correct, but it is still pointless as a `map` is a pointer already so `make()` is the correct thing to use, not `new()`. – Nick Craig-Wood Nov 08 '12 at 09:47
  • That's not true. The previous example showed that using a map doesn't require "making" it (e.g. `m := map[t]u{}`, although it is `make`ed by compiler magic). Secondly, map is not a pointer type and even though we know that actually it is implemented as a pointer to some run time structures, still pointers to pointers do have completely legitimate uses. There is nothing wrong in `new(anyType)` per se. The design/intent might be wrong, but that's a different topic. – zzzz Nov 08 '12 at 10:25
-5

Here is a difference: for a Person struct, the JSON string marshalled from &[]*Person{} is [] and from new([]*Person) is null using json.Marshal.

Check out the sample here: https://play.golang.org/p/xKkFLoMXX1s

Fisher
  • 359
  • 3
  • 5