Carson
Carson

Reputation: 17741

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

Upvotes: 3

Views: 348

Answers (1)

Stephen Weinberg
Stephen Weinberg

Reputation: 53398

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

Upvotes: 8

Related Questions