using new vs. { } when initializing a struct in Go

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

using new vs. { } when initializing a struct in Go

问题

在Go语言中,可以使用两种不同的方式初始化结构体。其中一种是使用new关键字,它返回一个指向内存中结构体的指针。另一种方式是使用{}来创建一个结构体。我的问题是什么时候适合使用每种方式呢?
谢谢。

英文:

So i know in go you can initialize a struct two different ways in GO. One of them is using the new keyword which returns a pointer to the struct in memory. Or you can use the { } to make a struct. My question is when is appropriate to use each?
Thanks

答案1

得分: 11

我更喜欢在完全知道类型的全部值时使用{},而在值逐步填充时使用new()

在前一种情况下,添加一个新参数可能涉及添加一个新的字段初始化程序。而在后一种情况下,应该将其添加到组成该值的任何代码中。

请注意,只有当T是结构体、数组、切片或映射类型时,才允许使用&T{}语法。

英文:

I prefer {} when the full value of the type is known and new() when the value is going to be populated incrementally.

In the former case, adding a new parameter may involve adding a new field initializer. In the latter it should probably be added to whatever code is composing the value.

Note that the &T{} syntax is only allowed when T is a struct, array, slice or map type.

答案2

得分: 8

根据@Volker的说法,通常最好使用&A{}来表示指针(这并不一定要使用零值:如果我有一个只包含一个整数的结构体,我可以使用&A{1}来初始化该字段)。除了风格上的考虑,人们通常更喜欢这种语法的主要原因是,与new不同,它并不总是在堆上分配内存。如果Go编译器可以确保指针永远不会在函数外部使用,它将简单地将结构体分配为局部变量,这比调用new要高效得多。

英文:

Going off of what @Volker said, it's generally preferable to use &A{} for pointers (and this doesn't necessarily have to be zero values: if I have a struct with a single integer in it, I could do &A{1} to initialize the field). Besides being a stylistic concern, the big reason that people normally prefer this syntax is that, unlike new, it doesn't always actually allocate memory in the heap. If the go compiler can be sure that the pointer will never be used outside of the function, it will simply allocate the struct as a local variable, which is much more efficient than calling new.

答案3

得分: 7

大多数人使用A{}来创建type A的零值,使用&A{}来创建指向type A零值的指针。只有对于int和类似的情况,使用new是必要的,例如int{}是不可行的。

英文:

Most people use A{} to create a zero value of type A, &A{} to create a pointer to a zero value of type A. Using newis only necessary for int and that like as int{} is a no go.

huangapple
  • 本文由 发表于 2014年2月28日 15:20:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/22088754.html
匿名

发表评论

匿名网友

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

确定