简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM