Clojure中with-local-vars和with-bindings之间的区别 [英] Difference between with-local-vars and with-bindings in Clojure
问题描述
Clojure的文档 with-local-vars
和 with-bindings
不足以区分两者。
The documentation for Clojure with-local-vars
and with-bindings
doesn't suffice for me to distinguish the two. Any hints?
推荐答案
新的 var
s由<$临时创建c $ c> with-local-vars 。现有的 var
暂时被 with-bindings
反弹。在两种情况下,绑定都是线程本地的。
New var
s are temporarily created by with-local-vars
. Existing var
s are temporarily rebound by with-bindings
. In both cases the bindings are thread-local.
请注意,据我所知, with-bindings
是告诉,主要用作通过使用 get-thread-bindings
返回的映射从另一个上下文传递绑定的助手。当不导入绑定时,类似的函数 binding
会更典型。
Note that with-bindings
is, as far as I can tell, primarily useful as a helper to pass bindings from another context by using a map returned by get-thread-bindings
. The similar function binding
would be more typical when not importing bindings.
说明性示例:
(binding [*out* (new java.io.StringWriter)]
(print "world!") (str "hello, " *out*))
;=> "hello, world!"
(with-local-vars [*out* (new java.io.StringWriter)]
(print "world!") (str "hello," *out*))
;=> world!"hello,#<Var: --unnamed-->"
(with-local-vars [foo (new java.io.StringWriter)]
(.write @foo "world") (str "hello, " @foo))
;=> "hello, world"
(binding [foo (new java.io.StringWriter)]
(.write @foo "world") (str "hello, " @foo))
;=> CompilerException java.lang.RuntimeException:
; Unable to resolve var: foo in this context...
这篇关于Clojure中with-local-vars和with-bindings之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!