Type parameter for each struct in `Vararg`

I think the nicest way to do this is to write your own function to get the V parameter from a MyStruct and then call that yourself, rather than going through the where machinery:

julia> struct MyStruct{T, V}
           x::T
           y::V
       end

julia> v_type(::MyStruct{T, V}) where {T, V} = V
v_type (generic function with 1 method)

julia> function f(args::Vararg{<:MyStruct})
         println("V types: ", v_type.(args))
       end
f (generic function with 1 method)

julia> f(MyStruct(1, 2.0), MyStruct(1, "hello"))
V types: (Float64, String)

This is just like using eltype for an AbstractArray. Sometimes it’s convenient to write code like:

function foo(x::AbstractVector{T}) where {T}
  println("got a vector of ", T)
end

But it’s just as efficient and sometimes more convenient to write:

function foo(x::AbstractVector)
  println("got a vector of ", eltype(x))
end
1 Like