`new(T)` 和 `&T{…}` 之间的区别是什么?

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

(Idiomatic?) Difference between new(T) and &T{...}?

问题

我开始尝试使用Go语言,并对new函数感到有些烦恼。它似乎相当有限,特别是在考虑到具有匿名字段或内联初始化的结构时。所以我阅读了规范,并在以下段落中发现了一些信息:

> 调用内置函数new或取一个复合字面量的地址会在运行时为变量分配存储空间。

因此,我怀疑new(T)&T{}会以完全相同的方式运行,这是正确的吗?如果是这样,那么在什么情况下应该使用new呢?

英文:

I started kidding around with Go and am a little irritated by the new function. It seems to be quite limited, especially when considering structures with anonymous fields or inline initialisations. So I read through the spec and stumbled over the following paragraph:

> Calling the built-in function new or taking the address of a composite literal allocates storage for a variable at run time.

So I have the suspicion that new(T) and &T{} will behave in the exact same way, is that correct? And if that is correct, in what situation should new be used?

答案1

得分: 5

是的,你说得对。new 在结构体中并不是那么有用。但对于其他基本类型来说是有用的。new(int) 会给你一个指向零值 int 的指针,而你不能使用 &int{} 或类似的方式。

无论如何,在我的经验中,你很少需要这样做,所以很少使用 new。你可以只声明一个普通的 int,并传递一个指向它的指针。实际上,这样做可能更好,因为它使你不必考虑在堆栈中分配还是在堆中分配,编译器会为你决定。

英文:

Yes, you are correct. new is not that useful with structs. But it is with other basic types. new(int) will get you a pointer to a zero-valued int, and you can't do &int{} or similar.

In any case, in my experience, you rarely want that, so new is rarely used. You can just declare a plain int and pass around a pointer to it. In fact, doing this is probably better because liberates you from thinking about allocating in the stack vs. in the heap, as the compiler will decide for you.

huangapple
  • 本文由 发表于 2015年1月25日 21:10:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/28136763.html
匿名

发表评论

匿名网友

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

确定