Wali Waqar
Wali Waqar

Reputation: 385

Parametric Types: Accept subtypes of a given type, but not the type itself

consider the following code:

abstract type MyDimension end
abstract type My2D <: MyDimension end
abstract type My3D <: MyDimension end

mutable struct Shape{T<:MyDimension}

end

Currently you can declare variables of type Shape{My2D}, Shape{My3D} and Shape{MyDimension}.

Is there any way that allows the first two but not Shape{MyDimension}?

Upvotes: 1

Views: 42

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69879

You can do:

mutable struct Shape{T<:Union{My2D, My3D}}
end

or create an intermediate type:

abstract type My2or3D <: MyDimension end
abstract type My2D <: My2or3D end
abstract type My3D <: My2or3D end
mutable struct Shape{T<:Union{My2or3D}}
end

The choice should be made considering if you want Shape to have a fixed types that it accepts or you want to potentially allow defining additional types that it accepts without having to redefine the Shape type.

Upvotes: 3

Related Questions