Binding variable from function which isn't defined in a closure to a closed variable

Hi, the goal is to get a shared variable between functions by defining a closure.
The following minimal working example works as intended:

disp, change = let x = [1,2]
    disp = () -> println(x)
    change = function()
        x .+= 1 
    end
    disp, change    
end

change()
disp()  # [2,3]
change()
disp() # [3,4]

I would like to have the same behaviour where the change function isn’t defined in the closure

change = function()
    x .+= 1 
end

disp, change = let x = [1,2], change=change
    disp = () -> println(x)
    # somehow bind this x to the x in change
    disp, change    
end

change()
disp() # [1,2] (wrong)
change()
disp() # [1,2] (wrong)

I’m guessing i’ll need some macro for this.
I tried @inline in the definition of change, but it didn’t work.

EDIT:
I know this works, but i was wondering if there is another way to do this

change = function(x)
    x .+= 1 
end
disp, change = let x = [1,2], change=change
    disp = () -> println(x)
    change_() = change(x)
    disp, change_    
end

change()
disp()  # [2,3]
change()
disp() # [3,4]

Closures in julia are syntactic sugar for (callable) structs.

The answer to all closure-related questions in julia should begin with “how would I do this without closures”, and possibly end with “but using closures, I can make this code look nicer (after verifying that both produce the same acceptable data layout and machine code)”.

In other words,

struct Change <: Function
x::Vector{Int}
end
(c::Change)()= begin c.x .+= 1; nothing end;

struct Disp <: Function
x::Vector{Int}
end
(d::Disp)() = println(d.x)

x = [1,2]; disp = Disp(x);change = Change(x);

julia> disp()
[1, 2]
julia> change()
julia> disp()
[2, 3]
1 Like

It might be that the example is oversimplfied, but note that this is perfectly fine if the type of x does not change:

julia> const x = [1,2]
2-element Vector{Int64}:
 1
 2

julia> change() = x .+= 1
change (generic function with 1 method)

julia> change()
2-element Vector{Int64}:
 2
 3

julia> change()
2-element Vector{Int64}:
 3
 4