在一些Julia代码中何时可以看到条件表达式,例如
if val !== nothing
dosomething()
end
其中
val
是Union{Int,Nothing}
类型的变量条件
val !== nothing
和val != nothing
有什么区别?
最佳答案
首先,通常建议使用isnothing
来比较是否是nothing
。此特定功能非常有效,因为它仅基于类型(@edit isnothing(nothing)
):
isnothing(::Any) = false
isnothing(::Nothing) = true
(请注意
nothing
是Nothing
类型的唯一实例。)关于您的问题,
===
和==
(以及!==
和!=
)之间的区别在于,前者检查两件事是否相同,而后者检查是否相等。为了说明这种差异,请考虑以下示例:julia> 1 == 1.0 # equal
true
julia> 1 === 1.0 # but not identical
false
请注意,前一个是整数,而后一个是浮点数。
两件事完全相同是什么意思?我们可以引用比较运算符的文档(
?===
):help?> ===
search: === == !==
===(x,y) -> Bool
≡(x,y) -> Bool
Determine whether x and y are identical, in the sense that no program could distinguish them. First the types
of x and y are compared. If those are identical, mutable objects are compared by address in memory and
immutable objects (such as numbers) are compared by contents at the bit level. This function is sometimes
called "egal". It always returns a Bool value.
有时,与
===
进行比较比与==
进行比较更快,因为后者可能涉及类型转换。
关于comparison - 使用!==或!=将Julia变量与 `nothing`比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56852880/