liveBook · Manning

Struct instance

As explained in Clojure: The Essential Reference

A struct instance is a map-like value created from a struct definition and containing its defined keys, possibly with nil values.

A struct instance is a map-like Clojure value created from a struct definition. It contains the definition’s keys, assigning nil to omitted keys, while accepting additional key-value pairs. section 11.1.4

Create and use struct instances through these operations:

  • Use create-struct or defstruct to define the required keys. section 11.1.4
  • Use struct for positional values; missing values become nil, and excess values raise IllegalArgumentException. section 11.1.4
  • Use struct-map for key-value initialization; defined keys default to nil when omitted. section 11.1.4
  • Use accessor to build a function that retrieves one key from instances; dissoc cannot remove a defined key. section 11.1.4

Normalize waypoint maps

(defstruct waypoint :type :lat :lon :id) (def coordinates [{:lat "18.3112" :lon "3.1314" :id "XVA"}]) (defn to-waypoints [coords] (map #(apply struct-map waypoint (mapcat identity %)) coords)) (to-waypoints coordinates) ;; ({:type nil, :lat "18.3112", :lon "3.1314", :id "XVA"})

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

Browse the compact API signatures for defining, constructing, and accessing struct instances. section 11.1.4

How Clojure: The Essential Reference covers it

How deep it goes
Explains definitions, constructors, defaults, accessors, ordering, and key-removal constraints through concise examples.
Examples
Uses waypoint records, coordinate-map normalization, positional construction, accessor functions, and map-like structure comparisons.
What it assumes
Assumes basic Clojure map and key-value knowledge, then teaches struct definitions and both initialization styles.
What you can do after
Apply it via create-struct, defstruct, struct, struct-map, and accessor to build and read constrained map-like values.
How it connects
Connects struct instances with maps, array-maps, defrecords, struct definitions, and accessor functions.

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.