I would say that this is not a bug.
AFAICT keys is a lazy iterator.
That means that for key in keys(s) does not compute a list of all valid keys and then
executes the loop but rather computes the next key(s) on the fly.
Since you keep adding elements to your dictionary, you end up with more unintended iterations.
Another example:
x = [0]
for el in x
push!(x, el+1)
println(el)
end
This gives you an infinite loop. In every iteration a new element has been added.
In general I would say that it is a bad idea to modify the iterator inside the for loop.
Your collect(keys(s)) is better.
Mm… It is counter-intuitive, isn’t it? Are we asking users to play computers, to be operational? What is the semantic definition of keys()? I am thinking from the point of view of language design.
Is it possible to design the iterators not to include the new keys? If not, maybe the documentation can help by emphasize the operational nature of keys() in the dictionary section and for iterators in general.
s = Dict(1=>‘a’)
for key in keys(s)
println(key)
s[key+1] = ‘x’
end
This time only the key 1 is printed. I have to agree with the statement “If you modify an iterator within the loop, all sorts of strange things can happen.”