[英]Does a method exist to check if a variable is Nothing or WhiteSpace?
我已經搜索了文檔,它似乎不存在,但您可以自己編寫。
function IsNullOrWhiteSpace(verify::Any)
# If verify is nothing, then the left side will return true.
# If verify is Nothing, then the right side will be true.
return isnothing(verify) || isa(nothing,verify)
end
function IsNullOrWhiteSpace(verify::AbstractString)
return isempty(strip(verify))
end
println(IsNullOrWhiteSpace(nothing)) # true
println(IsNullOrWhiteSpace(" ")) # true
可能不是最好的方法,但它確實有效。
為什么我們需要isnothing()
和isa()
?
讓我們看看當我們將isnothing()
與nothing
和Nothing
一起使用時會發生什么。
println(isnothing(nothing)) # true
println(isnothing(Nothing)) # false
我們顯然想處理Nothing
,我們該怎么做呢?
使用isa()
,它將測試nothing
是否是Nothing
的類型。
比其他答案稍微優雅一點的方法是充分使用多重調度:
isNullOrWS(::Type{Nothing}) = true
isNullOrWS(::Nothing) = true
isNullOrWS(verify::AbstractString) = isempty(strip(verify))
isNullOrWS(::Any) = false
這實際上也導致了更快的匯編代碼。
julia> dat = fill(Nothing, 100);
julia> @btime isNullOrWS.($dat);
174.409 ns (2 allocations: 112 bytes)
julia> @btime IsNullOrWhiteSpace.($dat);
488.205 ns (2 allocations: 112 bytes)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.