Still trying to wrap my head around the type system of Julia.
Any explanation why this is not allowed, and what would be the best way to achieve something similar?
struct State{T::Int}
end
Is the only way to achieve that through conditions in the inner constructor? If yes, why is that because it would let users “materialize” type that are not constructible. It might be better to raise the error earlier.
You can look at how they do it for SArray in their source code. Like you suggested they just use a check in the inner constructor (check_array_parameters), which is defined here.
In Julia, you can’t dispatch on a value such as true or false . However, you can dispatch on parametric types, and Julia allows you to include “plain bits” values (Types, Symbols, Integers, floating-point numbers, tuples, etc.) as type parameters. A common example is the dimensionality parameter in Array{T,N} , where T is a type (e.g., Float64) but N is just an Int .
You can use Symbols but not Strings. None of the two are a “plain bits” type, Symbol is kinda of the only exception to this rule, but String follows the rule: it is not a “plain bits” type and therefore its valuescannot be used as type parameters.
I do sometimes wish we could do the constraints you’re asking for. I remember @jameson explained to me once that it’s a good thing you can create these hypothetical types. I’m not sure I found the explanation very satisfying, but I do place a lot of trust in his insight.
julia> using StaticArrays
julia> struct Test{N,T}
x :: SVector{N,T}
end
julia> Test(SVector{3,Int}(0,0,0))
Test{3,Int64}([0, 0, 0])
That will fail if N is not an integer, because of the constructor for the SVector. (But as pointed above the constraint, if you want to anticipate it, has to be written in the inner constructor).