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には影響しないので、 を返します。 xthread-bound?false

によって作成されたを参照するには、x(not )を使用する必要があります。例えば:(var x)varwith-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内の新しい var に字句的にのみバインドされます。with-local-varsを参照する関数を呼び出すとx、グローバル が参照されxます。

を動的に再バインドする場合は、使用して動的xにする必要があります。bindingx

(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 に答える