comparison - 使用!==或!=将Julia变量与 `nothing`比较

标签 comparison julia nothing

在一些Julia代码中何时可以看到条件表达式,例如

if val !== nothing
    dosomething()
end

其中valUnion{Int,Nothing}类型的变量

条件val !== nothingval != nothing有什么区别?

最佳答案

首先,通常建议使用isnothing来比较是否是nothing。此特定功能非常有效,因为它仅基于类型(@edit isnothing(nothing)):

isnothing(::Any) = false
isnothing(::Nothing) = true

(请注意nothingNothing类型的唯一实例。)

关于您的问题,=====(以及!==!=)之间的区别在于,前者检查两件事是否相同,而后者检查是否相等。为了说明这种差异,请考虑以下示例:
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/

相关文章:

java - 获取一个 ArrayList,其中包含某些对象类型的两个不同大小的 arraylist 的并集

python:哪个文件更新了多少时间

julia - 如何在 Juno 中创建类似于 IJulia 或 R Notebook 的 Julia 笔记本

.net - 将 String.Empty 转换为 Nothing/Null

scala - 理解scala.Nothing类型

vb.net - 为什么要在 Finally block 中将对象设置为 Nothing?

c - NULL 指针与零段错误的比较

c# - 为什么使用泛型的 "Equals"方法解析与显式调用不同

fortran - 从 Julia 调用 Fortran 子例程。数组有效,但整数无效

javascript - 将 Ref{Cwstring}() 转换为字符串