In Toast, we have an internal server on a domain socket that accepts JSON and converts that JSON to Rust structs. One of the structs looks like this, with an
enum for the
There are a few ways to represent something like this in JSON.
serdein this case) can figure out which type it should be based on the available fields.
There are roughly three ways to tag types: externally, internally, and adjacent.
An externally tagged type uses a value outside of the content to tell the parser what type the content is. In this case we use the key of an object, where the value is the type.
Internally tagging types places a field that explicitly tells us which type it is inside the object with the other fields. In this case, we use a
Adjacently tagged types have separate fields for the type and the content next to each other. In this case we have a
type field next to a
We went with internally tagged types for Toast because they are a bit easier to write and understand for the people who will be writing them (JS devs). We also chose to overload a
value field so that the name of the field is always the same, yielding one less thing to remember when swapping back and forth between the two
modes. Example JSON payload looks like this:
There are also a couple tests here. This example compiles and you can check it out on the Rust playground if you want.