Hello,
I need to create a constructor with a parametric type to be able to dispatch. One possible way is the following
abstract type MyType end
# Singletons occupying 0 bytes
struct Type1 <: MyType end
struct Type2 <: MyType end
struct MyStruct{T<:MyType,MT<:AbstractArray}
data::MT
type::T
end
and I can call it with x = MyStruct(rand(10), Type1())
for example.
I could even remove the type
field from the struct, and just leave the parametric type, but I prefer to be able to call x.type
.
Now, do I really need to define the constructors to just have some types to use for multiple dispatch? Is the use of “standard” types better here? I mean something like
abstract type MyType end
# or primitive types?
abstract type Type1 <: MyType end
abstract type Type2 <: MyType end
struct MyStruct{T<:MyType,MT<:AbstractArray}
data::MT
type::Type{T} # Note the Type here
end
This would allow to define the object without parentheses, with something like x = MyStruct(rand(10), Type1)
, which I prefer.
Do you recommend this second method?
Alternative method
Or can I just do a mix of the two?
abstract type MyType end
# Singletons occupying 0 bytes
struct Type1 <: MyType end
struct Type2 <: MyType end
struct MyStruct{T<:MyType,MT<:AbstractArray}
data::MT
type::Type{T} # Note the Type here
end
and then calling MyStruct(rand(10), Type1)
so that I don’t have to put the parentheses.
Which method do you recommend? Is it a good way to work with types rather than struct
s?
If this method works, I was trying to implement the following function
function MyStruct(data; type::Union{Nothing, Type{T}} = nothing) where T
if isnothing(type)
_type = Type1
else
_type = T
end
return MyStruct(data, _type)
end
But I get type instabilities when doing MyStruct(rand(3); type=Type2)
for example.