简体   繁体   中英

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).

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM