簡體   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