I figured out today that one can "store data" in type parameters, like in:
struct Z{T1, T2}
x::T1
end
I don't even know if this is a good idea, but the language allows it. I was wondering how to instantiate objects of type Z
. I figured I can do this, for example:
julia> Z(x) = Z{typeof(x), 10}(x)
Z
julia> Z(1)
Z{Int64, 10}(1)
Is there a better way to define the Z
constructor? For example, avoiding the ugly typeof(x)
?
You could write
Z(x::T) where T = Z{T, 10}(x)
If the data is ‘static data’ which you expect to be type stable and you want your programs to specialize on it, then yes this is a very useful pattern.
For instance, if you inspect a NamedTuple, you’ll find that it stores the ‘names’ this way
Thanks, that was very useful!
I do this in AVRDevices.jl - it's incredibly useful if you know that something is a constant in your code for any given object and you need it often when working with that object
Yep; that's where I thought this could be useful. I just had never written structs with parameters that were not related to the types of its fields.
A perhaps familiar exsmple: The Array type stores the dimension as the second type parameter.
Indeed -- but somehow it never clicked for me that the dimension parameter is actually arbitrary; I still considered it to be somehow dependent on the type, if that makes sense.
I think part of my problem (beyond obtuseness) is that the documentation almost always associates type parameters to field types, although to be fair it does mention the case of arrays, and it sort of hints at this functionality in the discussion on value types.
Last updated: Nov 06 2024 at 04:40 UTC