what should be used New() or var in go?

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

what should be used New() or var in go?

问题

如何为结构体创建对象?

object := new(struct)

或者

var object struct

我不太理解何时使用哪种方式?如果两种方式都可以,应该优先选择哪一种?

英文:

How a object should be created for a struct?

object := new(struct)

or

var object struct

I could not understatnd when to use what? and if both are same which one should be prefered?

答案1

得分: 5

你展示的new语法返回一个指针,而另一种语法返回一个值。你可以查看这篇文章:https://golang.org/doc/effective_go.html#allocation_new

实际上,还有一种我更喜欢的选项,它被称为复合字面量,看起来像这样:

object := &struct{}

上面的示例等同于你使用new的方式。它的有趣之处在于你可以在大括号中为struct的任何属性指定值。

在何时使用哪种方式是一个需要根据具体情况做出的决定。在Go语言中,我会根据以下几个原因选择其中之一:也许只有指针*myType实现了某个接口,而myType没有实现;一个实例myType可能包含大约1GB的数据,你希望确保将指针而不是值传递给其他方法等。选择使用哪种方式取决于具体的用例。虽然我要说的是,指针很少会更差,因为这种情况很少发生,所以我几乎总是使用指针。

英文:

The new syntax you're showing returns a pointer while the other one is a value. Check out this article here; https://golang.org/doc/effective_go.html#allocation_new

There's actually even one other option which I prefer. It's called composite literal and looks like this;

object := &struct{}

The example above is equivalent to your use of new. The cool thing about it is you can specify values for any property in struct within the brackets there.

When to use what is a decision you need to make on a case by case basis. In Go there are several reasons I would want one or the other; Perhaps only the pointer *myType implements some interface while myType does not, an instance myType could contain about 1 GB of data and you want to ensure you're passing a pointer and not the value to other methods, ect. The choice of which to use depends on the use case. Although I will say, pointers are rarely worse and because that's the case I almost always use them.

答案2

得分: 4

当你需要一个指针对象时,使用new或复合字面量,否则使用var

尽可能使用var,因为这样更有可能在堆栈中分配内存,并且内存会在作用域结束时立即释放。如果使用new,内存很可能在堆中分配,并且需要进行垃圾回收。

英文:

When you need a pointer object use new or composite literal else use var.

Use var whenever possible as this is more likely to be allocated in stack and memory get freed as soon as scope ends. I case of new memory gets allocated most likely in heap and need to be garbage collected.

huangapple
  • 本文由 发表于 2015年7月22日 05:31:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/31549980.html
匿名

发表评论

匿名网友

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

确定