I kinda newbee and have an architecture problem on go & interface: I need to store info about Vehicle and assume it could be Car, Bus, Ambulance, Firetruck etc. So Vehicle is interface and every exact Vehicle type is struct, but all of them have some common fields (colour, number of wheels, seats, mufflers etc) and when I need to get something common I can go following ways:
- Don't use interface at all and have one big struct with a lot of getters and setters checked every time "if vehicle type X can have field Z?". It makes those methods very hard to read and very easy to forget to check smthng.
- Perform type assert every time on every type to get exact field. So just to get colour I will need to write type switch for 10 lines.
- Add to interface getter for every common field:
type Vehicle interface {
Colour() string
Wheels() int
Seats() int
Mufflers() int
...
}
As I see it's anti-pattern for "keep interface small" and will produce a lot of very similiar code (same method for every struct)
- Have some struct like CommonVehicle which store all common fields and all other vehicle type embed it and interface have only method return this CommonVehicle:
type Vehicle interface {
Common() CommonVehicle
}
type CommonVehicle struct {
// common fields
}
type Car struct {
CommonVehicle
// uncommon fields
}
// implementation for Vehicle interface
When I need to get colour I will do vehicle.Common().Colour. It looks clear on interface and types side, but it could mislead to call every time Common to get anything from Vehicle.
What is the best practice for this? Maybe I missed something and need to go some other way?