Parametrize a struct with numbers not types

Structs parametrized with types are common,

struct coo{T} where {T}

Is it possible to parametrize a struct with numbers, like integers? For example, suppose I want to classify all n-component vectors as a struct named ‘coordinates’, with a parameter ‘n’ indicating the number of components, how can I do?

1 Like

I’m not the best person to answer your question, though I brought some inspiration from Meshes.jl’s primitives and points.

They have roughly the following:

abstract type Primitive{Dim,T} <: Geometry{Dim,T} end

struct Point{Dim,T} <: Primitive{Dim,T}
  Point(coords::Vec{Dim,T}) where {Dim,T} = new{Dim,T}(coords)

const Point1 = Point{1,Float64}

You can find more details in the linked files (and I learned a lot from this package as a whole as well). Hope this helps.

1 Like

Yes, you can have data as parameters, provided the data is “bits” - i.e. contain no pointers, and is not mutable.
The built-in type BitArray, for example, have a number as a type parameter:

julia> BitArray{2}(undef, (3, 5))
3×5 BitMatrix:
 0  0  0  0  0
 0  0  0  0  0
 0  0  0  0  0

Any type, too. The most immediately encountered example is Array{T, N}; Vector{T} is an alias for Array{T, 1}.

There is a difficulty there because a struct definition can’t vary the number of fields to match a parameter value (after all, how could you name them at definition if they vary). However, you could have 1 field of the struct hold a NTuple{n, T}, which is a special alias for Tuple that allows you to specify number of elements instead of each type, precisely for cases like this. However, for Vector-like functionality, you’ll want to use SVector or some other type from StaticArrays.jl, which are internally based on tuples. Bear in mind that this approach is best when you have few values for n and they are small; if n varies a lot or gets large, it hurts rather than helps performance. StaticArrays.jl suggests 100 elements at most, which far more than enough for most use cases involving coordinates.


I implemented a similar idea here where I have an abstract type for all coordinates with a parameter N to indicate the number of dimensions that each coordinate type occupies.