new()和“常规”分配之间有什么区别吗?

huangapple go评论91阅读模式
英文:

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

问题

在Go语言中,上述两段代码有明显的区别吗?

v := &Vector{} 与 v := new(Vector) 有什么不同?

英文:

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

v := &Vector{}

as opposed to

v := new(Vector)

答案1

得分: 53

不. 它们返回的是相同的,

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))
}

结果:

*main.Vector
*main.Vector

邮件列表上有一些争议,认为同时存在两者会令人困惑:

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

需要注意的一点是:

> new() 是获取指向未命名整数或其他基本类型的指针的唯一方法。你可以写成 "p := new(int)",但你不能写成 "p := &int{0}"。除此之外,这只是个人偏好。

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

英文:

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

答案2

得分: 25

是的,这两个代码片段之间有根本的区别。

v := &Vector{}

仅适用于Vector是结构体类型、映射类型、数组类型或切片类型。

v := new(Vector)

适用于任何类型的Vector

示例:http://play.golang.org/p/nAHjL1ZEuu

英文:

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

答案3

得分: -5

这里有一个区别:对于一个Person结构体,从&[]*Person{}序列化得到的JSON字符串是[],而从new([]*Person)序列化得到的是null,使用的是json.Marshal

在这里查看示例:https://play.golang.org/p/xKkFLoMXX1s

英文:

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

huangapple
  • 本文由 发表于 2012年11月6日 13:30:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/13244947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定