# Copy a function

**URL:** <https://discourse.julialang.org/t/copy-a-function/99884>\
**Category:** General Usage\
**Tags:** functions\
**Created:** [June 5, 2023, 10:21am UTC](https://discourse.julialang.org/t/copy-a-function/99884 "2023-06-05T10:21:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![fedoroff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fedoroff/32/53209_2.png) [@fedoroff](https://discourse.julialang.org/u/fedoroff)\
**Post date:** [June 5, 2023, 10:21am UTC](https://discourse.julialang.org/t/copy-a-function/99884/1 "2023-06-05T10:21:36Z")

</div>

Let’s say I want to store a function in a struct.To do this, I pass this function to the constructor of the structure. However, if at some point later I redefine the original function, then the function inside the structure will also change, which is not desirable for me:

```julia
struct MyStruct{F}
    func :: F
end

foo(x) = 2*x

s = MyStruct(foo)

println(foo(2)) # 4
println(s.func(2)) # 4 desirable output 

foo(x) = 4*x

println(foo(2)) # 8
println(s.func(2)) # 8 undesirable output

```

Is there a way to copy the function `foo` so that the stored function `func` will not be affected by any subsequent redefinition of `foo` ? Unfortunately, `copy` and `deepcopy` do not work.

---

<div class="post-metadata">

**Author:** ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)\
**Post date:** [June 5, 2023, 10:53am UTC](https://discourse.julialang.org/t/copy-a-function/99884/2 "2023-06-05T10:53:02Z")

</div>

Standard functions are singleton, there is one and only one instance of them possible.  
Use anonymous functions instead,

```julia
foo = x -> 2x

```

---

<div class="post-metadata">

**Author:** ![fedoroff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fedoroff/32/53209_2.png) [@fedoroff](https://discourse.julialang.org/u/fedoroff)\
**Post date:** [June 5, 2023, 11:51am UTC](https://discourse.julialang.org/t/copy-a-function/99884/3 "2023-06-05T11:51:20Z")

</div>

Thank you.
