andrew cooke
andrew cooke

Reputation: 46882

How to populate a Clojure record from a map?

Is there something like struct-map for records? If not, should I use a struct (the docs discourage use of structs)?

Maybe I am doing the wrong thing completely? I have a rather complex function which currently takes a map of options. I am trying to clarify what option values are acceptable/used (by replacing it with a record). And now I want to interface that to code that has this information in maps (and which contain a superset of the data in the record).

Upvotes: 11

Views: 2544

Answers (1)

amalloy
amalloy

Reputation: 91907

It's not recommended to use records simply for "documentation" - plain old maps are more flexible, simpler, and easier. For documentation, you can merely add a docstring, or a comment, or create a function like (defn make-whatever [thing1 thing2]).

If you still want a record, you have a couple choices depending on whether you're using clojure version 1.3 or higher. If so, (defrecord Whatever ...) also defines a map->Whatever function, and a ->Whatever function that takes positional args. If not, you can write (into (Whatever. nil nil nil) some-map) (passing the right number of nils for the record type).

Upvotes: 20

Related Questions