问题
In some Julia code when can see conditional expression such as
if val !== nothing
dosomething()
end
where val
is a variable of type Union{Int,Nothing}
What is the difference between conditons val !== nothing
and val != nothing
?
回答1:
First of all, it is generally advisable to use isnothing
to compare if something is nothing
. This particular function is efficient, as it is soley based on types (@edit isnothing(nothing)
):
isnothing(::Any) = false
isnothing(::Nothing) = true
(Note that nothing
is the only instance of the type Nothing
.)
In regards to your question, the difference between ===
and ==
(and equally !==
and !=
) is that the former checks whether two things are identical whereas the latter checks for equality. To illustrate this difference, consider the following example:
julia> 1 == 1.0 # equal
true
julia> 1 === 1.0 # but not identical
false
Note that the former one is an integer whereas the latter one is a floating point number.
What does it mean for two things to be identical? We can consult the documentation of the comparison operators (?===
):
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.
Sometimes, comparing with ===
is faster than comparing with ==
because the latter might involve a type conversion.
来源:https://stackoverflow.com/questions/56852880/comparing-julia-variable-to-nothing-using-or