How can i index a tuple type?

Hey,

Say i have a tuple type Tuple{A,B}. How can i index it to ge the nth type ? I have the following error:

julia> Tuple{Float64,Int64}[1]
ERROR: MethodError: Cannot `convert` an object of type Int64 to an object of type Tuple{Float64, Int64}
Closest candidates are:
  convert(::Type{T}, ::T) where T<:Tuple at essentials.jl:315
  convert(::Type{T}, ::Tuple{Vararg{Any, N}}) where {N, T<:Tuple} at essentials.jl:316
  convert(::Type{T}, ::CartesianIndex) where T<:Tuple at multidimensional.jl:137
  ...
Stacktrace:
 [1] setindex!(A::Vector{Tuple{Float64, Int64}}, x::Int64, i1::Int64)
   @ Base .\array.jl:839
 [2] getindex(#unused#::Type{Tuple{Float64, Int64}}, x::Int64)
   @ Base .\array.jl:392
 [3] top-level scope
   @ REPL[72]:1

julia> 

I dont want to instantiate the Tuple type to index a tuple and then get the type.

3 Likes

If T is the type of your tuple, then T.types[1] will provide the type of the first element.

2 Likes

Is this an implementation detail or something that can be relied upon changes of minor version?

2 Likes

Looks like T.parameters also gets there. Dunno if it can be relied upon however

not very reliable, more importantly, the order can definitely change

1 Like

Inspired by this line from Base:

tuple_type_head(T::Type) = fieldtype(T, 1)

It looks like fieldtypes(T,n) should do the job, which is exported. However, the comment just above that line, and the fact that it is in deprecated.jl calls for caution…

1 Like