Uninitialized ("random") value of bits type

question

#1

I need a “placeholder” value of a (parametric) bits type, for type stability, in certain branches of my code. Ie I need a function f such that f(T) isa T. When T <: Number, zero(T) works, but I need something more general.

I am not sure what the best way of doing this is though. I thought of the following:

any_value1(T) = reinterpret(T, Vector{UInt8}(sizeof(T)))

any_value2(T) = Vector{T}(1)[1]

any_value3(T) = unsafe_get(Nullable{T}())

All work, yet I pity my future self who is going to read any of them later on. Is there anything more idiomatic?


#2

Can you use local x::T ?

function f(y)
       local x::Float64
       for i in 1:y
         x = 1.0 * i
       end
       x
end

#3

Nullable was exactly designed for that. In Julia 0.7, the performance of Union{T, Void} has been/will be improved so that it no longer kills performance.


#4

I am aware of this, I am looking for the language construct which can serve as a building block for things that make up something similar to, say, Nullable. The latter sidesteps the issue above by using incomplete initialization. One can of course use something similar, eg

struct AnyValue{T}
    value::T
    AnyValue{T}() where T = new{T}()
end
any_value4(T) = AnyValue{T}().value