Computed type annotations for struct fields

Is there a way to make this work in Julia:

##
function relative(t::Type{Int64})
    Float64
end

function relative(t::Type{Int32})
    Float32
end

struct Foo{T}
  a::relative(T)
  b::T
end

x = Foo{Int64}(2.0, 1)

This is a common and useful pattern in c++.

What about:

relative(::Int64) = Float64
relative(::Int32) = Float32
struct Foo{T1,T2}
    a::T1
    b::T2
end
Foo(a, b::T) where T = Foo{relative(b), T}(a, b)

x = Foo(2.0, 1)
y = Foo(2.0, Int32(1))
2 Likes

Computed field types have been an issue for several years. It’s on the 2.0 milestone list.

2 Likes

If you want this to be a guarantee rather than just a convenience thing you can also make it an inner constructor so its impossible to construct the object in an “inconsistent” state:

struct Foo{T1,T2}
    a::T1
    b::T2
    Foo(a, b::T) where T = new{relative(b), T}(a, b)
end
2 Likes