在Julia中初始化空变量

3

如何在Julia中为可能为空的变量编写初始化?

id = nothing
title = "Something"
hash  = "31114"

id = id || title || hash # Not working

2
它“不工作”的方式是什么?你的确切预期输出是什么? - Tasos Papastylianou
不清楚你的问题是什么。如果你想知道 id 是否有意义,你应该使用 isdefined。如果你想区分空和“空值”,你应该使用 Some(nothing)。如果你试图执行布尔测试,你应该选择可以轻松转换为布尔值的类型。 - Tasos Papastylianou
关于被接受的答案,请注意 something(nothing, 0)something(Some(nothing), 0) 之间的区别。如果 "nothing" 是数据集中的合法值,则需要注意它。这个问题听起来有点像一个寻找问题的 XY 解决方案。无论你在做什么,似乎最好将三元组包装在某种结构中(例如 Dict 或 Dataframe),并检查缺失值等。 - Tasos Papastylianou
@TasosPapastylianou 如果你试图执行它,它会抛出一个错误。在JS中,这是一种常见的构造方式来初始化变量,我正在寻找类似于Julia的东西。something解决了这个问题,谢谢。 - Alex Craft
1个回答

8

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"

请注意,在这种情况下,“missing”可能更为适合。 - Antonello
1
“missing” 对于这种模式并不一定更好。相反,如果您不希望未初始化的值悄无声息地传播,那么“nothing”才是正确的选择。 - Milan Bouchet-Valat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接