In Julia, declare AbstractVector{AbstractVector}

Viewed 219

I'm interested in defining a struct that has a field which is a vector of vectors. Potentially (but not necessarily), the inner vectors would be of type SVector (defined in the StaticArrays package). My naive approach would be to declare the field x::AbstractVector{AbstractVector{T}}; however, julia doesn't regard, say, Vector{SVector{3, Float64}} to be an instance of AbstractVector{AbstractVector}. For that matter, it doesn't regard Vector{Vector{64}} to be AbstractVector{AbstractVector} either. It seems as though the contained type has to be a concrete type, or left out entirely. Am I going about this in the wrong way?

2 Answers

Use AbstractVector{<:AbstractVector} as this is a construct accepting any vector whose element type is a subtype of AbstractVector.

Instead AbstractVector{AbstractVector} requires element type to be AbstractVector exactly.

Using structs with abstract fields are not generally recommended, especially for performance reasons. In a struct field AbstractVector{<:AbstractVector} is abstract, even if the eltype is concrete.

Using AbstractVector{<:AbstractVector} in a function signature is fine, but probably not in a struct definition. Try this instead:

struct Foo{T<:AbstractVector{<:AbstractVector}}
    x::T
end

This will give you a concretely typed field, where the type of the field x is encoded in the type parameter.

Related