在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发布于 2013-04-01 05:07:31
因为在您的示例中,x是到包含var的变量的本地绑定。#'x是(var x)的缩写,它会将x解析为当前名称空间中的全局变量。因为with-local-vars不影响全局x,所以thread-bound?返回false。
您需要使用x (而不是(var x))来引用with-local-vars创建的var。例如:
(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 2https://stackoverflow.com/questions/15732102
复制相似问题