# Function factories or callable structs?

**URL:** <https://discourse.julialang.org/t/function-factories-or-callable-structs/52987>\
**Category:** General Usage\
**Tags:** parametric-types, function\
**Created:** [January 7, 2021, 1:21pm UTC](https://discourse.julialang.org/t/function-factories-or-callable-structs/52987 "2021-01-07T13:21:15Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)\
**Post date:** [January 7, 2021, 1:39pm UTC](https://discourse.julialang.org/t/function-factories-or-callable-structs/52987/2 "2021-01-07T13:39:20Z")

</div>

I prefer the `struct`-based strategy because:

1. ~~For each type `T` you use there will be one type of `Adder{T}`. The function factory strategy will create different closures (each with a different type) each time you run it, even with the same value. It seems to me, therefore, that the function factory strategy overspecializes.~~ I was wrong about this, see @rdeits answer below. If the closures come all from the same factory (i.e., outer function) they will have the same type for the same type of captured variables (if the compiler infer the types right, see the second point). So, for the examples above it would be the same. The `struct` approach can give you a finer control over specialization, as you can decide how much you want to parametrize the `struct` type over the captured variables, and you know the type is the same being built inside any function.
2. There are some performance problems with closures, while I am not sure if they would affect your specific case: [https://github.com/JuliaLang/julia/issues/15276#issuecomment-628844489](https://github.com/JuliaLang/julia/issues/15276#issuecomment-628844489) Basically, closures often lose type information of captured bindings and end up boxing them unnecessarily.
3. You can use a `mutable struct` to change the boxed value if you need it, and if you do not then you can use an immutable `struct` which (I think) it is ~~more lightweight than a closure~~ EDIT: seems like they are about the same, as [closures lower to anonymous immutable structs](https://github.com/JuliaLang/julia/pull/31253).

---

_[View the full topic](https://discourse.julialang.org/t/function-factories-or-callable-structs/52987)._
