简体   繁体   English

通过命名空间关键字访问 map 值

[英]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?给定 clojure 中的 map, {::my-func {:meta {...}, :fn #function[hugsql.core/db-fn*]} ,自动定义,我如何检索:fn 值?

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.这是在 hugsql/map-of-db-fns 和 hugsql/def-db-fns 的上下文中。

::x is a short-cut for writing a namespaced keyword for the current ns. ::x是为当前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.所以这对源代码或 REPL 中的作者来说是一种方便,但实际上并没有打印出来。 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.所以可以预料,这里在某个时候出了问题,打印的::my-func实际上是关键字。 Clojure does not allow such a keyword, but the function to create them happily accepts any nonsense. Clojure 不允许这样的关键字,但是创建它们的 function 乐于接受任何废话。

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.无效关键字比仅使用字符串更危险,它会改变含义(如:bro ken broken 、 ::bork:bork,bork )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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