繁体   English   中英

使用!==或!=将Julia变量与“ nothing”进行比较

[英]Comparing Julia variable to `nothing` using !== or !=

在一些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.

有时,与===比较要比与==比较快,因为后者可能涉及类型转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM