What are tagged unions?

A tagged union is like a magical box that can hold different kinds of toys, but you always know which toy is inside.

Imagine you have a special bag called a box. This bag isn’t just for one type of toy, like only balls or only blocks. It can be a ball, a block, a car, or even a dinosaur, and you can tell what's inside by looking at a little label on the outside of the bag.

That label is the tag, and it tells you what kind of toy is inside the box (which is like the union). So if you see the tag says “ball,” you know to play catch. If it says “block,” you build a tower.

This is how tagged unions work in computer programs, they hold different kinds of data, and the tag tells you what kind of data it is.

Why It’s Useful

Think about a game where you can collect coins or find keys. The bag (or box) might have a coin inside one time and a key another time. With a tagged union, the program knows whether to count the coin or use the key, just by looking at the label!

It makes things easier for computers because they don’t have to guess what’s inside, they know exactly what they’re working with.

Take the quiz →

Examples

  1. A tagged union is like a box that can hold different kinds of toys, but you know which toy it is by looking at a label on the box.

Ask a question

See also

Discussion

Recent activity