liveBook · Manning

Record

As explained in Clojure: The Essential Reference

A database row is one record in a relational table, containing a value for each applicable column.

A Clojure record is an immutable, map-like value with named fields. Use one when several values share a small, meaningful shape and need a generated type, rather than just a collection of keys. `defrecord` creates the type; its instances support keyword lookup and map operations such as `assoc` and `dissoc`. section 15.7 section 11.0

Create and read a record

(defrecord Point [x y]) (def p (map->Point {:x 1 :y 2})) (:x p) ;; 1 (.x p) ;; 1 `map->Point` accepts a map; keyword lookup and field access both read the declared value. section 15.7

A record behaves like a map, but its type matters:

  • Records support `=`, can serve as hash-map keys, and can carry metadata. Equality is based on attributes. section 15.7 section 6.0
  • A record can implement interfaces and work with protocols, making it useful when data also needs behavior. section 15.7 section 15.0
  • `coll?` returns true for a record, but `(empty record)` throws `UnsupportedOperationException`: removing its integral fields would not produce an empty instance of the same type. section 8.1.4

Prefer `defrecord` to the older `defstruct` for a custom map-like type. A struct guarantees a defined minimum set of keys, but records also provide the generated type used with interfaces and protocols. Neither is a reason to replace every ordinary map: records are intended for a modest number of named fields. section 11.1.4 section 11.0

How Clojure: The Essential Reference covers it

How deep it goes
Explains construction, lookup, map semantics, interfaces, and an `empty` exception without detailing generated-class internals.
Examples
Demonstrates a point with keyword and field access, a sortable point implementing `Comparable`, and an address rejected by `empty`.
What it assumes
Assumes familiarity with Clojure maps and keyword lookup while showing record construction directly.
What you can do after
Build it from scratch with `defrecord`, access its fields, and recognize when a record differs from a map or struct.
How it connects
Connects records to maps, structs, `deftype`, interfaces, protocols, equality, and collection operations.

Also explained in

Compare how 12 books explain record →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.