在Go中声明带有“ var”的新结构实例与使用“ new”有何不同?
问题描述:
The following code creates a usable instance of the struct, Car
. How is this different than using new(Car)
?
Example:
type Car struct {
make string
}
func Main() {
var car Car; // how is this different than "car := new(Car)"?
car.make = "Honda"
}
以下代码创建了结构 示例: p>
Car code>的可用实例。 与使用
new(Car) code>有什么不同? p>
type Car struct {\ n生成字符串
}
func Main(){
var car Car; //这与“ car:= new(Car)”有何不同?
car.make =“ Honda”
}
code> pre>
div>
答
One defines a Car variable, the other returns a pointer to a 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:
var x Car
car := &x