philipbohun.com

Glojure by Example: Records

defrecord defines a named map type and a constructor. ->Point builds a value. Record values support the same keyword lookup and assoc as maps, and they remember their type.

(defrecord Point [x y])

(def p (->Point 3 4))
(println p)
(println (:x p))
(println (assoc p :y 9))

(defn manhattan [point]
  (+ (:x point) (:y point)))

(println (manhattan p))

Positional constructors are functions. Records are the usual replacement for a small Go struct when the data is Clojure data. Go structs from the host are a separate thing, covered with methods and fields.

(println (map->Point {:x 1 :y 2}))

A record prints with its type name.

$ glj records.glj
#Point{:x 3, :y 4}
3
#Point{:x 3, :y 9}
7
#Point{:x 1, :y 2}

Next example: Protocols.