Clojure with-local-vars
和with-bindings
的文档不足以让我区分这两者。任何提示?
答案 0 :(得分:11)
var
临时创建新的with-local-vars
。现有var
暂时被with-bindings
反弹。在这两种情况下,绑定都是线程本地的。
请注意,就我所知,with-bindings
主要用作帮助器,通过使用get-thread-bindings
返回的映射来传递来自另一个上下文的绑定。不导入绑定时,类似的函数binding
会更典型。
说明性示例:
(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...
答案 1 :(得分:2)
(with-bindings)期望绑定 映射的键是Vars,而不是符号 。它将给定的var / values映射推送到线程本地绑定的堆栈上并注意 返回给定函数后删除它。这是一个低级别的功能。
(with-local-vars)允许您以命令式样式(变异状态)进行编码。