我正在使用以下代码来创建命名空间,将当前命名空间中的给定符号列表及其值注入(inject)新命名空间并切换到新命名空间:
(defn in-ns-with-vars
"Switch to a new namespace (creating it if necessary) and
inject the given symbols into the new namespace
with the values they resolve to in the current namespace."
[new-ns-symbol & symbols-to-inject]
(let [n (create-ns new-ns-symbol)
current-value-of (fn [v] @(ns-resolve (the-ns *ns*) v))]
(do
(doseq [v symbols-to-inject]
(intern new-ns-symbol v (current-value-of v)))
(in-ns new-ns-symbol)
(clojure.core/refer 'clojure.core))))
是否有实现这一目标的现有机制?由于在脚本上下文中的使用,当前(初始)命名空间是静态未知的,因此我无法静态引用它。
最佳答案
您可以使用 alias
,而不是创建一个指向旧 var 值的新 var。或 refer
使用捕获的运行时符号 *ns*
使绑定(bind)在新创建的命名空间中可见。
user=> ((juxt identity type) (.name *ns*))
[user clojure.lang.Symbol]
关于clojure - 切换命名空间时保留变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28813432/