Modelling JSON with an Enum

Rust's enums are the perfect fit for a recursive data format.

Part 1 of 3Updated

JSON has exactly six kinds of value. In Rust that’s one enum:

#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    Null,
    Bool(bool),
    Number(f64),
    String(String),
    Array(Vec<Value>),
    Object(Vec<(String, Value)>),
}

This is a sum type — a Value is exactly one of these, and the compiler will force you to handle every case when you match on it. In a language with only classes you’d reach for inheritance and a cast; here the shape of the data is the type.

Array(Vec<Value>) is recursive, and that’s fine because Vec heap-allocates. A bare Array(Value) would be infinitely sized and rejected.