在Clojure中向前声明一个var从另一个命名空间? [英] Forward-declaring a var from another namespace in Clojure?

查看:121
本文介绍了在Clojure中向前声明一个var从另一个命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何转发声明一个var为当前的命名空间。相反,我想声明一个var从另一个命名空间。我如何做到这一点?这将帮助我消除循环负载依赖。

I know how to forward declare a var for the current namespace. Instead, I want to declare a var from another namespace. How do I do this? This will help me eliminate a circular load dependency.

现在,这是我试过的:

; this_ns.clj
(ns my-project.this-ns
  (:require ...))
(ns my-project.other-ns)
(declare other-func)
(ns my-project.this-ns) ; return to original namespace
(defn func-1
  []
  (my-project.other-ns/other-func))

推荐答案

p>我认为你已经有的解决方案是最简单的。如果你将它包装到一个宏,它甚至看起来不再坏:

I think the solution you already have is the easiest one. If you wrap it into a macro it doesn't even look that bad anymore:

(defmacro declare-extern
  [& syms]
  (let [n (ns-name *ns*)]
     `(do 
        ~@(for [s syms]
            `(do 
               (ns ~(symbol (namespace s)))
               (declare ~(symbol (name s)))))
        (in-ns '~n))))

调用它:

(declare-extern my.extern.ns/abc) ;; => #<Namespace ...>
my.extern.ns/abc                  ;; => #<Unbound Unbound: #'my.extern.ns/abc>

这篇关于在Clojure中向前声明一个var从另一个命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆