Is there a difference between new() and "regular" allocation?

Go

Go Problem Overview


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

v := &Vector{}

as opposed to

v := new(Vector)

Go Solutions


Solution 1 - Go

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

Solution 2 - Go

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

Solution 3 - Go

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLincoln BergesonView Question on Stackoverflow
Solution 1 - GominikomiView Answer on Stackoverflow
Solution 2 - GozzzzView Answer on Stackoverflow
Solution 3 - GoFisherView Answer on Stackoverflow