0

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?

1 Answer 1

3

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"}
Sign up to request clarification or add additional context in comments.

1 Comment

That works thanks. I had a different issue that caused the straight forward answer not to work. Now the world makes sense again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.