简体   繁体   中英

accessing map value by namespaced keyword

given a map in clojure, {::my-func {:meta {...}, :fn #function[hugsql.core/db-fn*]} , automagically defined, how do I retrieve:fn value?

I've tried

(get-in map [:my-func :fn])
(get-in map [::my-func :fn])
(get-in map [:current-namespace/my-func :fn])
(get-in map [:namespaces-it-could-be/my-func :fn])

this is in context of hugsql/map-of-db-fns and hugsql/def-db-fns.

::x is a short-cut for writing a namespaced keyword for the current ns.

user=> ::x 
:user/x 

So this is a convenience for the writer of the source or in the REPL, but does not actually get printed. Neither directly as seen above or inside maps

user=> {::x 1}
#:user{:x 1}
user=> {::x 1 :y 2}
{:user/x 1, :y 2}

So it's to be expected that something went wrong here at some point and the printed ::my-func is actually the keyword. Clojure does not allow such a keyword, but the function to create them happily accepts any nonsense.

user=> (keyword ":my-func")
::my-func
user=> {(keyword ":my-func") 42}
{::my-func 42}
user=> (let [dont (keyword ":my-func") m {dont 42}] (get m dont))
42

Rule of thumb: don't keywordize things, you don't have in your own hands. It's just as easy to use string keys for things others have defined for you. There is way more danger in invalid keywords, that change the meaning (like :bro ken , ::bork , :bork,bork ), than to just use strings.

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