英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论