使用 declare 时 Lein 测试未绑定 var 失败

Lein test failing on unbound var when using declare

为什么使用 lein test 运行 时以下测试的最后一个断言失败?

我不明白为什么前两个断言正确地获得了后期绑定值,但 fromvar 值被视为未绑定。

(declare x)

(def fromvar x)
(defn fromfun [] x)

(deftest declaretest

  ;; These pass fine
  (is (= 1 x))
  (is (= 1 (fromfun)))

  ;; This fails on lein test:
  ;; expected: (= 1 fromvar)
  ;;   actual: (not (= 1 #<Unbound Unbound: #'my-test/value>))
  (is (= 1 fromvar)))

(def x 1)

def 不能确保 fromvar 绑定到 value 的绑定。它在调用 def 时将 x 的值分配给 fromvar。由于尚未定义 x,因此该值未绑定(字面上是内部 class Var.Unbound 的实例)。 fromfun在编译时没有内联x的值,所以在运行时可以自由找到正确的值,反映后面的赋值。