Generic Associated Types

Hi, I am looking to define a type as below:

gat1(::Type{Float64}) = Int64
gat2(::Type{Float64}) = String

struct Foo{T}
    a::gat1(T)
    b::gat2(T)
end

f = Foo{Float64}(10, "Hello")

Is there any way to get generic assoicated types in Julia?

I am unsure if it is still maintained but you may find GitHub - jonniedie/ConcreteStructs.jl: πŸ©πŸ πŸŒ†πŸ¨πŸŒ‡πŸ¦ useful (+ using whatever inner constructor you want to pass values into the struct)

You want ComputedFieldTypes.jl:

julia> using ComputedFieldTypes

julia> gat1(::Type{Float64}) = Int64
gat1 (generic function with 1 method)

julia> gat2(::Type{Float64}) = String
gat2 (generic function with 1 method)

julia> @computed struct Foo{T}
           a::gat1(T)
           b::gat2(T)
       end

julia> Foo{Float64}(10, "Hello")
Foo{Float64, Int64, String}(10, "Hello")
3 Likes

There’s no way around aliasing an underlying Foo{T, U, V}, otherwise associating types like that makes unstable concrete types. Say after the code example, you redefine gat1(::Type{Float64}) = Ref{Int32}. Now Foo{Float64} refers to a different underlying type.