Golang:3种创建新实例的方式,但有什么区别?(初学者)

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

Golang: 3 ways to create a new instance but what's the difference? (Beginner)

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对Golang还不太了解,根据我目前所学,创建结构体有三种不同的方式:

a := MyStruct{} // 普通的按值方式。这种方式叫什么名字?
b := new(MyStruct) // 使用new关键字
c := &MyStruct{} // 使用引用

示例

我不清楚每种方式之间的实际区别,除了发现在使用“普通”方式时,打印对象的内存地址时需要添加引用符号&,例如 fmt.Printf("%p\n", &a),而使用“new”和“引用”方式时则不需要,例如 fmt.Printf("%p\n", b)。我猜测这是因为使用“普通”方式分配内存的方式不同,但这只是我的猜测。

看起来使用“new”和“引用”方式是等效的选项,选择其中一种是一种风格上的决定?在这种语言中,是否有惯用的偏好方法?还有其他我尚未发现的方式吗?

英文:

I'm new to Golang and from what I've learned so far there are 3 different ways to new up a struct:

a := MyStruct {}  // plain by value style. Is that what this is called?
b := new(MyStruct) // using new
c := &MyStruct {} // using a reference

Example

I'm not clear as to the actual differences between each of these other then I've found that I have to add a reference & symbol when printing the memory address of the object like this fmt.Printf("%p\n", &a) when using the "plain" style vs fmt.Printf("%p\n", b) for the "new" and "reference" styles. My assumption is that this is because using the "plain" style allocates memory differently but this is just a guess.

It appears that using the "new" and "reference" styles are equivalent options so choosing between those to is a stylistic decision? Is there an idiomatic preference in this language as to which method I should use? Are there other styles that I've not discovered yet?

答案1

得分: 2

《Go编程语言规范》是一本重要的参考资料,其中包括了复合字面量、分配、变量声明和短变量声明等内容。

在代码示例中,a := MyStruct {} 是一个复合字面量值,b := new(MyStruct) 是一个指向该类型零值的指针,c := &MyStruct {} 是一个指向复合字面量值的指针。ac 是非常常见的用法,而 b 则相对较少见,大多数情况下会使用 c

你可以参考《Go之旅》中的示例代码。

英文:

> The Go Programming Language Specification
>
> Composite literals
>
> Allocation
>
> Variable declarations
>
> Short variable declarations

a := MyStruct {}  
b := new(MyStruct) 
c := &MyStruct {} 

a is a composite literal value. b is a pointer to a zero value for the type. c is a pointer to a composite literal value. a and c are very common. b is uncommon, in most cases, c is used.

Take the Tour of Go for examples.

huangapple
  • 本文由 发表于 2016年2月14日 13:06:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/35388559.html
匿名

发表评论

匿名网友

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

确定