Allocation: new(Foo) vs Foo{}

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

Allocation: new(Foo) vs Foo{}

问题

以下是创建对象的两种语法的区别以及为什么会有两种不同的方法,尽管结果是相同的。

第一种语法是使用结构体字面量初始化对象:

type Foo struct {
    X int
}

f1 := &Foo{}

在这种情况下,我们使用&操作符创建了一个指向Foo类型的指针,并将其初始化为空对象。

第二种语法是使用new关键字创建对象:

f2 := new(Foo)

在这种情况下,我们使用new关键字创建了一个指向Foo类型的指针,并将其初始化为空对象。

尽管两种方法都可以创建一个空的Foo对象,但它们在语义上有一些微妙的区别。

使用结构体字面量初始化对象时,我们可以在初始化时设置字段的初始值。例如,我们可以使用以下方式初始化X字段的值:

f1 := &Foo{
    X: 10,
}

而使用new关键字创建对象时,所有字段都将被初始化为其类型的零值。在上面的例子中,f2X字段将被初始化为0

因此,尽管两种方法都可以创建相同的对象,但使用结构体字面量初始化对象可以更方便地设置字段的初始值。

英文:

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)

答案1

得分: 10

使用new是直接返回本地类型(intfloat64uint32等)的指针的唯一方法,而不需要先创建一个普通变量,然后返回指向它的指针。

关于这个问题在以下链接中有更详细的讨论:https://groups.google.com/forum/#!topic/golang-nuts/K3Ys8qpml2Y 和 https://groups.google.com/forum/#!topic/golang-nuts/GDXFDJgKKSs,但基本上它是无用的。

Dave Cheney的引述如下:

> new不会消失,它不能消失,它是Go 1的规范的一部分。
>
> 你不需要使用它,大多数人都不使用,但这并不意味着它没有用处。

英文:

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.

huangapple
  • 本文由 发表于 2014年7月28日 21:12:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/24996101.html
匿名

发表评论

匿名网友

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

确定