liveBook · Manning

Struct constructor

As explained in Clojure: The Essential Reference

A struct constructor is a Clojure function that creates a struct instance by matching supplied values positionally to a struct definition's keys.

A struct constructor creates a map-like struct instance by assigning supplied values positionally to the keys in a struct definition. Define the keys with create-struct or defstruct, then call struct with the definition and values. section 11.1.4

Constructing a waypoint

(defstruct waypoint :type :lat :lon :id) (struct waypoint "VHF" "0.000000" "0.000000" "ABI") ;; {:type "VHF", :lat "0.000000", :lon "0.000000", :id "ABI"} For parsed rows, (apply struct waypoint values) turns each value sequence into a waypoint. Passing more values than defined keys raises IllegalArgumentException. section 11.1.4

Listing 11.4. → Constrained Map, Guarded keys
(create-struct [& keys])
(defstruct [name & keys])
(struct-map [s & inits])
(struct [s & vals])
(accessor [s key])

Use the compact API listing to compare struct with create-struct, defstruct, struct-map, and accessor. section 11.1.4

How Clojure: The Essential Reference covers it

How deep it goes
Explains positional mapping, definitions, output shape, and excess-value errors, but does not detail constructor implementation internals.
Examples
Uses waypoint records parsed from whitespace-separated rows and constructs them with apply.
What it assumes
Assumes familiarity with Clojure maps and function application while defining struct keys from the API.
What you can do after
Builds struct instances from definitions and positional values, including batches of parsed data.
How it connects
Connects struct with struct definitions, defstruct, create-struct, struct-map, accessor, maps, and defrecord.

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.