Clojure with-local-vars
和with-bindings
的文档不足以让我区分两者。有什么提示吗?
with-local-vars
临时创建新的var
。现有的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...
(带绑定)希望绑定映射的键是Vars,而不是符号。它将给定的var/values映射推送到线程本地绑定的堆栈上,并注意在给定函数返回后将其删除。这是一个低级函数。
(使用本地变量)允许您以命令式(可变状态)进行编码。