[英]How is declaring a new struct instance with “var” different from using “new” in Go?
The following code creates a usable instance of the struct, Car
. 以下代码创建了一个可用的结构实例
Car
。 How is this different than using new(Car)
? 这与使用
new(Car)
什么不同?
Example: 例:
type Car struct {
make string
}
func Main() {
var car Car; // how is this different than "car := new(Car)"?
car.make = "Honda"
}
One defines a Car variable, the other returns a pointer to a Car. 一个定义一个Car变量,另一个定义一个指向Car的指针。
var car Car // defines variable car is a Car
car2 := new(Car) // defines variable car2 is a *Car and assigns a Car to back it
car := new(Car)
can be implemented in relation to var car Car
like this: car := new(Car)
可以实现与var car Car
:
var x Car
car := &x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.