I thought I understood "pass-by-sharing" in Julia until I found this

In the OP case, as other have already pointed out, I think the root of the problem lies in a very common misunderstanding about the scope of for loops.

A for block does not define a single scope, but a succession of scopes one for each iteration.

The distinction between a single scope and a succession of scopes is often little relevant (I believe this is the reason for it being a common misunderstanding). However, together with closures it become relevant and crashes a mental model in which all iterations shared the same inner scope.

I think it can be illustrated by:

julia> function f()
           for i = 1:5
               if @isdefined x
                   println("x found: $x")
               else
                   println("x not found")
               end
               x = i
           end
           return
       end
f (generic function with 1 method)

julia> f()
x not found
x not found
x not found
x not found
x not found
14 Likes