Type parameter for each struct in `Vararg`

I have the function f(args::Vararg{MyStruct{T, V}}) where {T,V}. However, I would actually like to allow the V's to be completely different (possibly not even promotable) for different elements of the Vararg, but I would still like to extract the type parameter for each.

For two arguments, this would look like f(arg1::MyStruct{T, V1}, arg2::MyStruct{T, V2}) where {T,V1,V2}. Is there any way to generalize this construct for a 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

Thanks, @rdeits I have tried your suggested method which has proven very effective. I am very happy to become this community. Hope to find more such educational information in the future.