想虚心请教...
什么,“用于常量值的 var 或 ref/atom/agent?”,我问?
当然,我确实将 vars 用于常量值。
但我总是想知道当值像常量一样时我应该使用哪一个,但它们应该在运行时分配,而不是在编译时(读取代码时)。
例如,想想用户的配置文件中编写的一些 java 属性。
它们应该在运行时分配,因为数据不在代码中。
但是它们也应该在读取数据之前定义,因为其他代码引用它们。
在这种情况下,
我什么时候使用'var's?:
我什么时候使用 ref/atom/agent?:
我不知道我应该用什么。
你在这些情况下使用什么?
'瓦尔的? '引用/原子/代理的?甚至“延迟”?
提前致谢。
最佳答案
如果您正在考虑的所有或一组“常数”可以在单个时间点学习,我们将其称为“属性”。
让我们做一个配置来“吸引他们”:
(defn resource [path]
(when path
(-> (Thread/currentThread) .getContextClassLoader (.getResource path))))
(def props
(edn/read-string
(slurp (io/file (resource (System/getProperty "your.conf"))))))
(defn conf [& path] ;; e.g. (conf :db :uri)
(get-in props (vec path)))
您的属性(例如“常量”)文件“your.conf”将在以下行中:
{:db
{:uri "datomic:mem://dbname"
:other-property 42}
:rabbit
{:host "192.168.1.17"
:port 5672
:exchange "xyz-exchange"
:queue "zq"
:exchange.type "direct"
:vhost "/some-broker"
:username "user"
:password "strong"}}
然后在您的程序/其他命名空间中,您可以访问所有这些属性:
(conf :db :uri) ;; will "constant"ly return "datomic:mem://dbname"
(conf :rabbit :host) ;; will "constant"ly return "192.168.1.17"
(conf :db :other-property) ;; will "constant"ly return 42
在“现实生活”中,上面的“ Prop ”变量可能会检查“-D”路径,具有默认值并处理异常,但为了说明这一点,它有点简化。
关于clojure - var 或 ref/atom/agent 用于常量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19994471/