在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
答案 0 :(得分:3)
因为在您的示例中,x
是对包含var
的变量的本地绑定。 #'x
是(var x)
的简写,它将x解析为当前命名空间中的全局。由于with-local-vars
不会影响全局 x
,thread-bound?
会返回false
。
您需要使用x
(而非(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