Records
8 min · OCaml
Group related values under named fields: OCaml's struct-like type.
Enemy 1 of 5
Creating and reading a record
A record bundles a fixed set of named fields, like a name and a score, into one value. OCaml checks every field's name and type for you.
This builds a record for a player named Ada, then prints the name field using dot notation. Press Run to see it.
Why this works
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.
Rena
Your AI tutor. She walks you through each step.
Asking for help is part of coding. Rena reads your code and gives you a hint. She is free with an account: 20 hints a day.