# Mutating closure?

**URL:** <https://discourse.julialang.org/t/mutating-closure/33544>\
**Category:** General Usage\
**Tags:** closure\
**Created:** [January 19, 2020, 12:00pm UTC](https://discourse.julialang.org/t/mutating-closure/33544 "2020-01-19T12:00:54Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mcreel](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mcreel/32/30088_2.png) [@mcreel](https://discourse.julialang.org/u/mcreel)\
**Post date:** [January 19, 2020, 12:00pm UTC](https://discourse.julialang.org/t/mutating-closure/33544/1 "2020-01-19T12:00:54Z")

</div>

I am trying to define a closure which mutates its argument, without luck. Is there a way to define a closure which is mutating? Here’s an example of what I’m trying to achieve:  
Thanks!

```julia
function a!(x)
    for i = 1:size(x,1)
        x[i] = 2.0 * x[i]
    end
    y = 1.0
    return x
end

function a!(x,y)
    for i = 1:size(x,1)
        x[i] = 2.0 * x[i]
    end
    y = [1.0]
    return x
end

function main()
    x = [1.0]
    y = [1.0]
    # one argument
    println("one argument")
    println("x before function", x)
    a!(x)
    println("x after function", x)
    f! = x -> a!(x)
    println("x before closure", x)
    f!(x)
    println("x after closure", x)
    # two arguments
    println("two arguments")
    println("x before function", x)
    a!(x,y)
    println("x after function", x)
    g! = x -> a!(x,y) #### THIS IS WHAT DOES NOT WORK.
    println("x before closure", x)
    g!(x,y)
    println("x after closure", x)
end

main()

```

---

<div class="post-metadata">

**Author:** ![Jakub\_Wronowski](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jakub_wronowski/32/204030_2.png) [@Jakub\_Wronowski](https://discourse.julialang.org/u/Jakub_Wronowski)\
**Post date:** [January 19, 2020, 1:42pm UTC](https://discourse.julialang.org/t/mutating-closure/33544/2 "2020-01-19T13:42:56Z")

</div>

> [@mcreel](#):
>
> y = [1.0]

It allocates new object in the second method, you probably want:  
`y[1] = 1.0`

Also later invocation of g! seems to be not correct. If `y` is catched into a closure, you should pass only `g!(x)`

---

<div class="post-metadata">

**Author:** ![mcreel](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mcreel/32/30088_2.png) [@mcreel](https://discourse.julialang.org/u/mcreel)\
**Post date:** [January 19, 2020, 3:15pm UTC](https://discourse.julialang.org/t/mutating-closure/33544/3 "2020-01-19T15:15:18Z")

</div>

Thanks! A silly mistake on my part. Now it’s working as I hoped it would.
