Clojure defrecord deftype
There are different ways to create a struct in clojure.
1) Using Clojure built in data structures
user> (def lotr {:title "Book title"
:author {
:first-name "first"
:last-name "last"}})
#'user/lotr
keyword-access
user> (:title lotr) "Book title"
nested-access
user> (-> lotr :author :first-name) "first"
2) Using defrecord
user> (defrecord Book [title author])
user.Book
user> (defrecord Person [first-name last-name])
user.Person
user> (def lotr (Book. "Book Title"
(Person. "first" "last")))
#'user/lotr
keyword-access
user> (:title lotr) "Book title"
nested-access
user> (-> lotr :author :first-name) "first"
As you can see, accessing map and defrecord is very similar. defrecord provides implementation of a persistent map.
3) Using deftype
PS: bad example ( I will explain why later )
user> (deftype Book [title author])
user.Book
user> (deftype Person [first-name last-name])
user.Person
user> (def lotr (Book. "Book Title"
(Person. "first" "last")))
#'user/lotr
Unlike defrecord, deftype does not provide implementation of a persistent map. So when you try to keyword-access , it won’t work
keyword-access
user> (:title lotr) nil
It provides field access only
user> (.title lotr) "Book Title"
I mentioned the above example for deftype is a bad example. Let me explain why. In OO, we have two set of classes. One set that defines language constructs like String and other that defines domain like Book. As defrecord provides implementation of a persistent map, it is better to use defrecord for realizing domain. Use deftype for realizing programming constructs.

I don’t see why deftype (example 3) would work at all, since your lotr was left undefined in this example. So, are all of the above methods equivalent? Does it matter which one I use??
Glen
November 16, 2010 at 4:43 pm
Hi Glen:
Thanks for pointing it out. I have updated the blog to include lotr declaration.
It does matter which one you use. As you can see keyword access is available only for map and defrecord and not for deftype.
So use defrecord or map for domain constructs and use deftyoe for program constructs.
– Siva Jagadeesan
Siva Jagadeesan
November 16, 2010 at 4:54 pm