在某些Julia代码中何时可以看到条件表达式,例如
if val !== nothing
dosomething()
end
其中val
是类型Union{Int,Nothing}
的变量
条件val !== nothing
和val != nothing
有什么区别?
答案 0 :(得分:5)
首先,通常建议使用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.
有时,与===
进行比较比与==
进行比较要快,因为后者可能涉及类型转换。