With a type declared like that, any access of the field x will be type
unstable, which means that Julia’s JIT compiler will emit much more
defensive, and thus slower, code.
The solution is to declare a *parametric* type:
type MyType{T<:Union{Int64, Float64}}
x::T
end
That way, MyType(3) and MyType(3.0) will now be instances of different
types, and the compiler can generate fast code. (You can still write
functions that dispatch on just MyType, so you don’t loose any expressive
power…)
// T
On Wednesday, October 28, 2015 at 5:10:09 AM UTC+1, Gnimuc Key wrote:
Avoid type Unions in fields ¶
>>
>> <http://docs.julialang.org/en/latest/manual/style-guide/#avoid-strange-type-unions>
>> type MyType
>> ...
>> x::Union{Void,T}
>> end
>
>
> I'm wondering whether it's a good style or not to write something like
> this:
>
> type MyType
> ...
> x::Union{Int64,Float64}end
>
> what's the side effects of using Union like this?
>