Creating an array of `nothing` of any size in Julia

I think you are looking for the Base.fill — Function.

fill(x, dims)

This creates an array filled with value x.

println(fill("nothing", (1,3)))

You can also pass a function Foo() like fill(Foo(), dims) which will return an array filled with the result of evaluating Foo() once.


The fill function can be used to create arrays of arbitrary values, but it's not so easy to use here, since you want a Vector{Union{Float64, Nothing}}. Two options come to mind:

A comprehension:

a = Union{Float64, Nothing}[nothing for _ in 1:3];
a[2] = 3.14;

>> a
3-element Array{Union{Nothing, Float64},1}:
  nothing
 3.14    
  nothing

Or ordinary array initialization:

a = Vector{Union{Float64, Nothing}}(undef, 3)
fill!(a, nothing)
a[2] = 3.14

It seems that when you do Vector{Union{Float64, Nothing}}(undef, 3) the vector automatically contains nothing, but I wouldn't rely on that, so fill! may be necessary.

Tags:

Julia