如何在Julia中为可能为空的变量编写初始化?
id = nothing
title = "Something"
hash = "31114"
id = id || title || hash # Not working
如何在Julia中为可能为空的变量编写初始化?
id = nothing
title = "Something"
hash = "31114"
id = id || title || hash # Not working
something
将返回第一个不等于nothing
的值。它支持可变数量的参数:
julia> something(0, nothing)
0
julia> something(nothing, "foo")
"foo"
julia> something(nothing, nothing, 1)
1
x = something(x, DEFAULT_VALUE)
您的示例可以使用:
julia> id = nothing
julia> title = "Something"
"Something"
julia> hash = "31114"
"31114"
julia> id = something(id, title, hash)
"Something"
id
是否有意义,你应该使用isdefined
。如果你想区分空和“空值”,你应该使用Some(nothing)
。如果你试图执行布尔测试,你应该选择可以轻松转换为布尔值的类型。 - Tasos Papastylianousomething(nothing, 0)
和something(Some(nothing), 0)
之间的区别。如果 "nothing" 是数据集中的合法值,则需要注意它。这个问题听起来有点像一个寻找问题的 XY 解决方案。无论你在做什么,似乎最好将三元组包装在某种结构中(例如 Dict 或 Dataframe),并检查缺失值等。 - Tasos Papastylianousomething
解决了这个问题,谢谢。 - Alex Craft