liveBook · Manning

Struct-map

As explained in Clojure: The Essential Reference

struct-map is a Clojure function that creates a struct instance from a struct definition and key-value pairs.

`struct-map` creates a Clojure struct instance from a struct definition and key-value pairs: `(struct-map s & inits)`. Use it when input arrives as named fields rather than values in a fixed order. section 11.1.4

The definition supplies the instance’s required keys:

  • Create a definition with `create-struct`, or bind one with `defstruct`. section 11.1.4
  • Pass initialization entries as alternating keys and values. Defined keys omitted from the entries receive `nil`; additional keys are retained. section 11.1.4
  • A defined key cannot be removed from the resulting struct with `dissoc`; that operation raises a `RuntimeException`. section 11.1.4

Normalize partially populated coordinates

```clojure (defstruct waypoint :type :lat :lon :id) (struct-map waypoint :lat "18.3112" :lon "3.1314" :id "XVA" :alt 150) ;; {:type nil, :lat "18.3112", :lon "3.1314", :id "XVA", :alt 150} ``` The missing `:type` becomes `nil`, while the extra `:alt` remains available. For a sequence of ordinary maps, `(map #(apply struct-map waypoint (mapcat identity %)) coordinates)` converts each map in the same way. section 11.1.4

Choose `struct` instead when values already match the definition’s key order: it assigns them positionally and rejects more values than defined keys. `struct-map` is also used in `clojure.xml`’s nested representation of XML nodes, with `:tag`, `:attrs`, and `:content` fields. For everyday Clojure programming, `defrecord` generally replaces the need for structs. section 11.1.4 section 22.1

How Clojure: The Essential Reference covers it

How deep it goes
Defines the signature, missing-key behavior, extra-key handling, and a conversion example without detailing implementation internals.
Examples
Converts partially populated coordinate maps and identifies the struct-map fields produced by XML parsing.
What it assumes
Assumes familiarity with Clojure maps and function application while defining how struct definitions are created.
What you can do after
Apply it via Clojure’s struct-map to fill absent defined keys with nil while retaining additional entries.
How it connects
Connects struct-map to create-struct, defstruct, positional struct, defrecord, and XML parsing.

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.