The key behavioral difference between these two is that with the non-parametric union version you can change both the value and the type of the field of a MyType object after construction, whereas in the parametric version you can change the value of the field after an object has been constructed, but not the type – since the object is either a MyType{Int} or a MyType{Float64}.
On Wed, Oct 28, 2015 at 3:21 AM, Gnimuc Key <gnimuc...@gmail.com> wrote: > that makes sense. many thanks! > > 在 2015年10月28日星期三 UTC+8下午3:14:26,Tomas Lycken写道: > >> 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? >>> >> >> >