Using push!() on an array with 'nothing' as its only value results in error

It’s a weird error but the problem is that 1 doesn’t fit within the eltype of your array:

julia> typeof(1) <: eltype(stack)
false

You can define one with a wider type, either just [] which has Any, or

julia> stack2 = Union{Nothing,Int}[]
0-element Array{Union{Nothing, Int64},1}

julia> push!(stack2, 1, nothing, 42)
3-element Array{Union{Nothing, Int64},1}:
  1
   nothing
 42

(I guess my first line is not the perfect way to think, as push!(stack2, 1.0) works… push! tries to convert if necessary.)

5 Likes