Zaz*_*Zaz 17 clojure forward-declaration
Clojure,有一个declare宏,允许您转发声明函数或变量.这似乎完全一样的功能def:无论(declare x)和(def x)创建#<Unbound Unbound: #'user/x>
何时应该(declare x)使用而不是(def x)?
Zaz*_*Zaz 19
双方declare并def做创建未绑定的变种,但有3个优点,使用declare:
(declare x y z){:declared true}declare可以说是更清晰和惯用(source declare):
(defmacro declare
"defs the supplied var names with no bindings, useful for making forward declarations."
{:added "1.0"}
[& names] `(do ~@(map #(list 'def (vary-meta % assoc :declared true)) names)))
Run Code Online (Sandbox Code Playgroud)
文档给出了答案:
=> (doc declare)
-------------------------
clojure.core/declare
([& names])
Macro
defs the supplied var names with no bindings, useful for making forward declarations.
Run Code Online (Sandbox Code Playgroud)
查看实现,很明显它declare是根据 定义的def,并提供了一些语法糖。所以从功能上来说,它们几乎是一样的。
优点declare是向后来的读者表明意图。(declare x y z)意味着我打算对这些符号进行前向声明,因为宏是useful for making forward declarations.
(def x) (def y) (def z)意味着我正在实习这些符号,但你不知道我是否打算给它们定义但忘记了,或者我是否正在做出前向声明,或者可能是其他微妙的东西。
因此,当您进行前向声明时,(declare x)应该优先考虑,以对代码的未来读者表示怜悯。(def x)