# In Julia, how to create a function that saves its own internal state?

**URL:** <https://discourse.julialang.org/t/in-julia-how-to-create-a-function-that-saves-its-own-internal-state/58457>\
**Category:** New to Julia\
**Tags:** question, function\
**Created:** [April 2, 2021, 5:21pm UTC](https://discourse.julialang.org/t/in-julia-how-to-create-a-function-that-saves-its-own-internal-state/58457 "2021-04-02T17:21:33Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [April 2, 2021, 7:01pm UTC](https://discourse.julialang.org/t/in-julia-how-to-create-a-function-that-saves-its-own-internal-state/58457/6 "2021-04-02T19:01:04Z")

</div>

Or a functor?

```julia
struct F
  state
end
(o::F)(x) = o.state + x

f = F(1)

f(2)
3

```

more specifically:

```julia
julia> Base.@kwdef mutable struct F
         state = nothing
       end
F

julia> function (o::F)()
         if o.state == nothing
           o.state = 1
         else
           o.state += 1
         end
       end

julia> f = F()
F(nothing)

julia> f()
1

julia> f()
2

julia> f()
3

julia> f.state # now this is part of the language, because f is an instance of F
3

```

---

_[View the full topic](https://discourse.julialang.org/t/in-julia-how-to-create-a-function-that-saves-its-own-internal-state/58457)._
