在 Julia 中不初始化任何变量

Ale*_*hin 3 julia

如何为 Julia 中什么都没有的变量编写初始化?

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

id = id || title || hash # Not working
Run Code Online (Sandbox Code Playgroud)

Dav*_*ela 8

something将返回第一个不等于 的值nothing。它支持可变数量的参数:

julia> something(0, nothing)
0

julia> something(nothing, "foo")
"foo"

julia> something(nothing, nothing, 1)
1
Run Code Online (Sandbox Code Playgroud)

您可以使用它来设置变量的默认值:

x = something(x, DEFAULT_VALUE)
Run Code Online (Sandbox Code Playgroud)

您的示例可以使用:

julia> id = nothing

julia> title = "Something"
"Something"

julia> hash  = "31114"
"31114"

julia> id = something(id, title, hash)
"Something"
Run Code Online (Sandbox Code Playgroud)