在go中应该使用什么New()或var?

问题描述:

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?

应如何为结构创建对象? p>

  对象:= new(struct)
  code>  pre> 
 
 

或 p>

  var object struct 
  code>   pre> 
 
 

我不能低估什么时候使用什么? 并且如果两者都相同,应该优先选择哪一个? p> div>

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.

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.