title: Julia: function inside a struct and method constructor
body: <p>What is the correct way to store a function in a struct constructor? And retrieve it? And change its parameters?</p>
  <p>I wrote some code back in version 0.4 to 0.5, which unsurprisingly no longer works. In words: I have a <code>struct-cum-method</code> named Model in which I define parameters and functional forms. And a similarly structured Solution in which I solve instances of the model. My purpose is to make multiple simulations of the model for different sets of parameters and functional forms. The code below is part of a module inside a package. I don't have a good handle on how to deal with the function type in <code>Julia 1.6</code> (something like the code below used to work).</p>
  <pre><code># Non-Parametric version of struct + outer method constructor
  # Model parameters and functions
  struct Model
      f::Function
      p::Float64
      n::Int64
  end
  function Model(; 
      f::Function = x -&gt; x + p,
      p::Float64 = 2.0,
      n::Int64 = 4
      )
      Model(f, p, n)
  end
  </code></pre>
  <p>This is the output of <code>Model()</code>:</p>
  <pre><code>julia&gt; m = Model()
  Model(var&quot;#2#4&quot;(), 2.0, 4)
  
  julia&gt; Model(p = 1.0)
  Model(var&quot;#3#5&quot;(), 1.0, 4)
  
  julia&gt; m.f
  #2 (generic function with 1 method)
  
  julia&gt; m.p
  2.0
  
  julia&gt; m.n
  4
  
  julia&gt; Model(f = x -&gt; x - p)
  Model(var&quot;#15#16&quot;(), 2.0, 4)
  
  
  julia&gt; m.f(1.0)
  ERROR: UndefVarError: p not defined
  Stacktrace:
   [1] (::var&quot;#2#4&quot;)(x::Float64)
     @ Main ./REPL[2]:2
   [2] top-level scope
     @ REPL[4]:1
  </code></pre>
  <p>I'd be grateful for pointers on where the code goes wrong and how to fix it. If at all recommended, I'd like a parametric struct.</p>