Records
8 min · OCaml
Group related values under named fields — OCaml's struct-like type.
Enemy 1 of 5
Creating and reading a record
Lists are great for a sequence of values of the *same* type, but plenty of real data is a fixed bundle of *different* kinds of values that belong together — a player's name (a string) and score (an int), for example. A record groups a fixed set of named fields into a single value, similar to a "struct" in C or an object's plain data in other languages, but with OCaml's type system checking every field's type and name at compile time.
A record's shape (which fields it has, and what type each one is) is normally declared once as a type definition before you build any values of that type — this lesson's examples assume such a type has already been declared, with a `name` field (a string) and either a `score` or `hp` field (an int), depending on the example.
`{ name = "Ada"; score = 10 }` builds a record value by naming each field and giving it a value, separated by semicolons — the same semicolon convention used inside list literals. Reading a field back out uses dot notation, `player.name`, which will look familiar if you've used objects or structs in other languages, even though under the hood an OCaml record is a plain, immutable data value rather than an object with methods.
Loading editor...