How do I define my own type based on Julia's pre-existing type?

Hello!

I am trying to perform a simple experiment and need some help.

I wish to make a copy of the AbstractVector type as such:

struct AbstractVectorCopy{T} <: AbstractVector{T}
    field::AbstractVector{T} 
end

Then I want to be able to fill it with values, exactly the same way as for the AbstractVector:

using StaticArrays
# This works using AbstractVector
AbstractVector{SVector{3,Float32}}(zeros(SVector{3,Float32},100))

# This does not work using the copy
AbstractVectorCopy{SVector{3,Float32}}(zeros(SVector{3,Float32},100))

Any way to make it properly act like an “AbstractVector” but through my “new” type?

Kind regards

Hi,

have you looked into the docs at this page: Interfaces · The Julia Language

The interface for arrays is described here: Interfaces · The Julia Language

When you implement these interfaces, your struct should be usable everywhere where AbstractVector is supported.

No I had not seen that, thank you!

Very unclear to me a lot of things, but I think I got the basics:

Base.size(S::AbstractVectorCopy) = (length(S.field),)
Base.IndexStyle(::Type{<:AbstractVectorCopy}) = IndexLinear()
Base.getindex(S::AbstractVectorCopy, i::Int) = S.field[i]

AbstractVectorCopy{SVector{3,Float32}}(zeros(SVector{3,Float32},100))

So that is a start, since that now works! :slight_smile:

https://docs.juliahub.com/Lazy/mi7Ul/0.15.0/autodocs/#Lazy.@forward-Tuple{Any,Any}

may come handy if you just want a wrapper

1 Like

Have you seen performance tips, the “Type declarations” section in particular: Performance Tips · The Julia Language

As explained in the first two subsections, “Avoid fields with abstract type” and “Avoid fields with abstract containers”, you probably don’t want to declare your field with an abstract type, for performance reasons.

1 Like