3

下面的代码创建了一个可用的结构实例,Car. 这与使用有什么不同new(Car)

例子:

type Car struct {
  make string
}

func Main() {
  var car Car; // how is this different than "car := new(Car)"?

  car.make = "Honda"
}
4

1 回答 1

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
于 2012-06-12T03:45:01.973 回答