`splice!` for vector of structs

I’m trying to splice! a custom structure into an array containing my custom structures, something like:

mutable struct MyType
    a::Int64
    b::Float64
    c::Bool
end
MyType() = MyType(0, 0.0, false)
myvec = [MyType() for i in 1:10]
splice!(myvec, 3:2, MyType(1, 1.0, true))

What Base functions do I have to define in order to do this? When I call , I get an error telling me

ERROR: MethodError: no method matching length(::MyType)

I define Base.length(x::MyType) = 1 but then need to define Base.iterate(::MyType). I’m guessing that my length extension should be something like Base.length(v::Vector{MyType}) instead (and similarly for iterate, but I’m not sure. Any help would be appreciated, thanks!

Try splice!(myvec, 3:2, [MyType(1, 1.0, true)]) (i.e., wrap the third argument in a vector). I think the problem is not that you need to define length and iterate for your object, but that the splice! method takes a collection of objects in the third argument to use as replacement, not just one replacement object.

2 Likes