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?
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:
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.