Get type of field in parametric type

Base.@pure get_type_parameter(x) = typeof(x).parameters[2]

That infers.

julia> Base.@pure get_type_parameter(x) = typeof(x).parameters[2]
get_type_parameter (generic function with 2 methods)

julia> @code_warntype get_type_parameter(rand(3))
Variables:
  #self# <optimized out>
  x <optimized out>

Body:
  begin
      return $(Expr(:invoke, MethodInstance for getindex(::SimpleVector, ::Int64), :(Main.getindex), :((Core.getfield)(Array{Float64,1}, :parameters)::SimpleVector), 2))
  end::Int64

The more general form

Base.@pure get_type_parameter(x,i) = typeof(x).parameters[i]

needs IPO from v0.7 to infer.

1 Like