Why this error in copyto!?

Consider the well known Squares

struct Squares count::Int end
Base.iterate(S::Squares, state=START) = state > S.count ? nothing : (state*state, state+1)
Base.length(S::Squares) = S.count

and

Enumerate(iter, start, step) = zip(Iterators.countfrom(start, step), iter)
Enumerate(Squares(6), 0, 2) |> println ∘ collect

If I choose START = 1 in Squares then I get

Tuple{Int64,Any}[(0, 1), (2, 4), (4, 9), (6, 16), (8, 25), (10, 36)]

If I choose START = 0 then I get

ERROR: LoadError: ArgumentError: destination has fewer elements 
than required. Stacktrace: [1] copyto!(...) at .\abstractarray.jl:665

Why this different behavior?

I think you misunderstand the iteration protocol. Starting from state = 0 will make length(::Squares) inconsistent with what the iterator does, hence the error.

1 Like