【问题标题】:Keep variables when switching namespace切换命名空间时保留变量
【发布时间】:2015-03-02 15:28:26
【问题描述】:

我正在使用以下片段创建命名空间,将当前命名空间中的给定符号列表及其值注入新命名空间并切换到新命名空间:

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

是否存在实现此目的的现有机制?由于在脚本上下文中的使用,当前(初始)命名空间是静态未知的,所以我不能静态引用它。

【问题讨论】:

  • 为什么不在新创建的命名空间中使用别名或引用*ns*
  • 这行得通;如果你把你的评论变成答案,我可以接受。

标签: clojure namespaces


【解决方案1】:

您可以将aliasrefer 与捕获的运行时符号*ns* 一起使用,以使绑定在新创建的命名空间中可见,而不是创建指向旧var 值的新var。

user=> ((juxt identity type) (.name *ns*))
[user clojure.lang.Symbol]

【讨论】:

    【解决方案2】:

    potemkin 库中的 import-vars 函数可以为您执行此操作(在使用 *ns* 引用您的原始命名空间之后)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 2020-09-20
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多