1

在文档中with-local-var

varbinding=> symbol init-expr

Executes the exprs in a context in which the symbols are bound to
vars with per-thread bindings to the init-exprs. The symbols refer
to the var objects themselves, and must be accessed with var-get and
var-set

但是为什么thread-local?返回false?

user=> (with-local-vars [x 1] (thread-bound? #'x))
false
4

1 回答 1

3

因为,在您的示例中,x是对包含var. #'x是 的简写(var x),它将 x 解析为当前命名空间中的全局变量。由于with-local-vars不影响全局 x,因此thread-bound?返回false

您需要使用x(not (var x)) 来引用var创建者with-local-vars。例如:

(def x 1)

(with-local-vars [x 2]
  (println (thread-bound? #'x))
  (println (thread-bound? x)))

输出:

false
true

另外,请注意with-local-vars不会动态重新绑定x. x仅在词法上绑定到with-local-vars块内的新 var。如果你调用一个引用的函数,x它将引用全局的x

如果要动态重新绑定x,则需要使用binding并使其x动态:

(def ^:dynamic x 1)

(defn print-x []
  (println x))

(with-local-vars [x 2]
  (print-x)) ;; This will print 1

(binding [x 2]
  (print-x)) ;; This will print 2
于 2013-03-31T21:07:30.800 回答