liveBook · Manning

Defstruct

As explained in Clojure: The Essential Reference

defstruct is a Clojure macro that establishes a var containing a struct definition.

defstruct is a Clojure macro that binds a named struct definition to a var. The definition guarantees a fixed set of keys while retaining map-like behavior. section 11.1.4

Define and populate a waypoint struct

(defstruct waypoint :type :lat :lon :id) (struct-map waypoint :type "VHF" :lat "0.0" :lon "0.0" :id "ABI") ;; {:type "VHF", :lat "0.0", :lon "0.0", :id "ABI"} (defn to-waypoints [coords] (map #(apply struct-map waypoint (mapcat identity %)) coords)) Missing defined keys appear with nil values, while additional keys can remain in the resulting map.

How Clojure: The Essential Reference covers it

How deep it goes
Explains the macro’s binding behavior and struct contract, then demonstrates construction; it defers broader implementation details.
Examples
Uses point definitions, waypoint records, coordinate conversion, accessor functions, and comparisons with maps and defrecord.
What you can do after
Build reusable struct definitions and create instances with struct, struct-map, and accessor functions.
How it connects
Connects defstruct with create-struct, struct-map, struct, 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.