使用”var”关键字声明一个新的结构实例与在Go中使用”new”有什么不同?

huangapple go评论81阅读模式
英文:

How is declaring a new struct instance with "var" different from using "new" in Go?

问题

以下代码创建了一个可用的结构体Car的实例。这与使用new(Car)有什么不同?

示例:

type Car struct {
  make string
}

func Main() {
  var car Car; // 这与"car := new(Car)"有什么不同?

  car.make = "Honda"
}
英文:

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"
}

答案1

得分: 8

var car Car // 定义变量car是一个Car类型的变量
car2 := new(Car) // 定义变量car2是一个*Car类型的变量,并将一个Car类型的变量赋值给它

car := new(Car) 可以这样实现与 var car Car 的关系:

var x Car
car := &x

英文:

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

huangapple
  • 本文由 发表于 2012年6月12日 11:25:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/10990174.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定