Widening the element type of an array?

This may be a rather unusual question but: I’d like to “widen” the element type of a given Array to an abstract type, such that the resulting array contains the same data as the original, but can store values of another type in some cells (obviously this is not in a critical part of my code, performance-wise).

Like this:

julia> my_widen(arr, typ) = copy!(similar(arr, typ), arr)

julia> a = [1, 2, 3];

julia> b = my_widen(a, Number); b[2] = 2.0; b
3-element Vector{Number}:
 1
 2.0
 3

julia> c = my_widen(a, Union{Int, Nothing}); c[2] = nothing; c
3-element Vector{Union{Nothing, Int64}}:
 1
  nothing
 3

Does something like this exist already?

julia> a = [1, 2, 3];

julia> Vector{Number}(a)
3-element Vector{Number}:
 1
 2
 3
4 Likes

Of course! How could I not think of trying this? Thanks a lot