何时使用“if”和“何时”在Clojure? [英] When to use "if" and "when" in Clojure?
问题描述
什么时候比另一个好?
是一个比另一个更快还是唯一的区别是返回false或nil?
When is one better than the other? Is one faster than the other or does the only difference is the return of false or nil?
推荐答案
使用 if
当你只有一个truthy和一个假的情况而你不需要一个隐含的 do
块。相反,当你只需要处理真实案例和隐式做
时,应该使用时
。速度没有区别,这是使用最惯用的风格。
Use if
when you have exactly one truthy and one falsy case and you don't need an implicit do
block. In contrast, when
should be used when you only have to handle the truthy case and the implicit do
. There is no difference in speed, it's a matter of using the most idiomatic style.
(if (my-predicate? my-data)
(do-something my-data)
(do-something-else my-data))
(when (my-predicate? my-data)
(do-something my-data)
(do-something-additionally my-data))
在 if
的情况下,如果我只会运行
返回一个真实的结果,而在 do-something
-predicate?时
的情况下,两个 do-something
和 do-something-additional
被执行。
In the if
case, only do-something
will be run if my-predicate?
returns a truthy result, whereas in the when
case, both do-something
and do-something-additionally
are executed.
这篇关于何时使用“if”和“何时”在Clojure?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!