user2505060
user2505060

Reputation: 121

Golang down casting struct

I'm relatively new at Go and struggling with initialising structs.

The classic example is

type Car struct {
    wheelCount int
}
type Ferrari struct {
   Car
   driver string
}

// Initialise Ferrari
f := Ferrari{Car{4},"Some Dude"}

My question is, how do I get a *Ferrari if I only have a *Car created with a constructor?

I would like to be able to to something like the following

func NewCar(wheels int) *Car{
    return &Car{wheels};
}

car := NewCar(4);
ferrari := Ferrari{car,"Some Dude"}; // ERROR cannot use car (type *Car) as type Car in field value

Am I approaching the problem incorrectly? Can one simply dereference the car somehow?

Upvotes: 0

Views: 873

Answers (1)

Ainar-G
Ainar-G

Reputation: 36279

The error message is pretty clear. You can't use Car as a pointer to Car. You need to either redefine your Ferrari to embed a pointer to Car

type Ferrari struct {
    *Car
    driver string
}

or to dereference the pointer in the literal:

ferrari := Ferrari{*car, "Some Dude"}

Upvotes: 3

Related Questions