以下代码创建结构的可用实例Car
。这与使用new(Car)
有什么不同?
示例:
type Car struct {
make string
}
func Main() {
var car Car; // how is this different than "car := new(Car)"?
car.make = "Honda"
}
答案 0 :(得分:8)
一个定义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)
可以像var car Car
这样实现:
var x Car
car := &x