Stream: helpdesk (published)

Topic: Storing data in type parameters


view this post on Zulip mbaz (Dec 22 2022 at 02:57):

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)?

view this post on Zulip Mason Protter (Dec 22 2022 at 03:11):

You could write

Z(x::T) where T = Z{T, 10}(x)

view this post on Zulip Mason Protter (Dec 22 2022 at 03:13):

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.

view this post on Zulip Mason Protter (Dec 22 2022 at 03:13):

For instance, if you inspect a NamedTuple, you’ll find that it stores the ‘names’ this way

view this post on Zulip mbaz (Dec 22 2022 at 14:20):

Thanks, that was very useful!

view this post on Zulip Sukera (Dec 22 2022 at 17:15):

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

view this post on Zulip mbaz (Dec 22 2022 at 17:26):

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.

view this post on Zulip Fredrik Bagge Carlson (Dec 22 2022 at 17:50):

A perhaps familiar exsmple: The Array type stores the dimension as the second type parameter.

view this post on Zulip mbaz (Dec 22 2022 at 18:13):

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: Oct 02 2023 at 04:34 UTC