Common Base Type#

Let’s say you have the need to store a variety of related things. In C/C++, Java, etc., you define a common type and things are related by being dervied from that type. For example, if you have a list of tools, each member is derived from some common class like Tool. The collection is instantiated for Tools. You dervive a specific tool, like a Scredriver or Hammer from Tool and put it in the collection. If this is an app for a hardware store, for example, we might track prices for Tools. But an individual tool might have more fields.

If there is no common base type, we can shoe-horn the reference to an untyped reference. For example, say we wanted to store a list of tools, vehicles, and games. The list might be a list of void* or Object, and we need to cast down to specific parent types. Using Java as an example, I get a member of the list and see if I can cast it to Tool. While it is possible to store unrelated things, we now have to tediously cast to a type.

Untyped languages, like JavaScript, Python, or Ruby, basically make everything an untyped list. You can store anything you want into a list. But it’s your problem to understand what to do with the returned value. I might be able to ascertain its type, but it is essentially the void* approach.

There is another way. For example, in C/C++ I can create a union with a type code. Then I store pointers to the union. To understand what’s in the union I have to look at the descriminant. It is a manual way of doing what Ada does with descriminant or variant types. It’s safer than void*, because I don’t need to cast to get back to the preferred type of the object.

But there’s another way that’s a little more interesting. Rust enums allow me to gather arbitrary types together. For example, let’s say I have a list of things for sale on my site.

enum MarketableProduct {
    Tool(ToolRef),
    Vehicle(VehicleRef),
    Game(GameRef, u32)
};

No I can create a list of MarketableProducts. The Rust match idiom allows me to identify the type of MarketableProduct, safely. This is very cool, but it would be nice if they built it out more. For example, I can’t say if some_product == MarketableProduct::Tool. I have to perform equality on the enum value and the value it holds.