# \`Core.Box\` around captured variable

**URL:** https://discourse.julialang.org/t/core-box-around-captured-variable/91299
**Category:** General Usage
**Tags:** closure, corebox
**Created:** [December 6, 2022, 11:39am UTC](https://discourse.julialang.org/t/core-box-around-captured-variable/91299 "2022-12-06T11:39:17Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![jlbosse](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlbosse/32/11274_2.png) [@jlbosse](https://discourse.julialang.org/u/jlbosse)
#### Post date: [December 6, 2022, 11:39am UTC](https://discourse.julialang.org/t/core-box-around-captured-variable/91299/1 "2022-12-06T11:39:17Z")

</div>

If I define a variable inside an outer function that generates a closure, this variable gets boxed inside the closer. Does this affect performance and if yes, how do I best avoid it?

Here is a simple MWE:

```julia
julia> function Adder(a)
           ncalled = 0
           function f(b)
               ncalled += 1
               @info "calling this adder for the $ncalled time"
               return a + b
           end
           return f
       end

julia> plus1 = Adder(1)
(::var"#adder#1"{Int64}) (generic function with 1 method)

julia> plus1.a
1

julia> plus1.ncalled
Core.Box(0)

```

---

<div class="post-metadata">

### Author: ![roflmaostc](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/roflmaostc/32/30123_2.png) [@roflmaostc](https://discourse.julialang.org/u/roflmaostc)
#### Post date: [December 6, 2022, 12:31pm UTC](https://discourse.julialang.org/t/core-box-around-captured-variable/91299/2 "2022-12-06T12:31:54Z")

</div>

That’s unfortunately a [known issue](https://github.com/JuliaLang/julia/issues/15276)

You can fix it by using a let

```julia
function f(a)
     g = let a=a
         function g(b)
              a + b
          end
      end
end

```

I’m on my phone, sorry for brevity

---

<div class="post-metadata">

### Author: ![jlbosse](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlbosse/32/11274_2.png) [@jlbosse](https://discourse.julialang.org/u/jlbosse)
#### Post date: [December 6, 2022, 1:24pm UTC](https://discourse.julialang.org/t/core-box-around-captured-variable/91299/3 "2022-12-06T13:24:33Z")

</div>

Ah, I thought that `let` should be the solution but didn’t know how exactly it went. Thanks!
