<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="254824" data-post-id="254824">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="tomkonidas" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/tomkonidas/120/22982_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  tomkonidas
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>It can also be done as a <code>case</code> if you are more comfortable with that.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">def new(attrs) do
  case struct(__MODULE__, attrs) do
    %{bytes: nil} = struct -&gt;
      %{struct | bytes: random_bytes()}

    struct -&gt;
      struct
  end
end
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="254824" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/what-is-the-most-idiomatic-way-to-construct-structs-with-complex-default-values/48727/12">Post #11</a>
	                </div>
	            </div>
              <div id="likers-container-254824" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="254824"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #11"></div>
  </section>
</div>
    <div class="postbit" id="254825" data-post-id="254825">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="msimonborg" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/msimonborg/120/26638_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  msimonborg
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Another option would be to just build the default opts with <code>Keyword.put_new_lazy/3</code>. Then you create the struct once without needing to update it, and you still only run the <code>random_bytes()</code> generator when necessary. I don’t know how this would compare performance-wise with the <code>with</code> statement plus the update.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">def new(attrs) when is_list(attrs) do
  attrs = Keyword.put_new_lazy(attrs, :bytes, &amp;random_bytes/0)
  struct(__MODULE__, attrs)
end

# optionally if you want to accept both list and map arguments
def new(attrs) when is_map(attrs), do: new(Enum.to_list(attrs))
</code></pre>
<p>I always use <code>__MODULE__</code> just in case I want to change the module name down the line, I don’t have to update anything else in that file.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="254825" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/what-is-the-most-idiomatic-way-to-construct-structs-with-complex-default-values/48727/13">Post #12</a>
	                </div>
	            </div>
              <div id="likers-container-254825" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="254825"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #12"></div>
  </section>
</div>
    <div class="postbit" id="254826" data-post-id="254826">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="tomkonidas" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/tomkonidas/120/22982_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  tomkonidas
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>The thing is <code>attrs</code> is an <code>Enumerable.t()</code>, so it can be a map or a keyword. So that is why i do it after i create the struct.</p>
<p>But yea very valid if you want to have the two functions as you showed</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="254826" data-batch-url="/posts/batch_likers">
                        3
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/what-is-the-most-idiomatic-way-to-construct-structs-with-complex-default-values/48727/14">Post #13</a>
	                </div>
	            </div>
              <div id="likers-container-254826" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="254826"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #13"></div>
  </section>
</div>
    <div class="postbit" id="254827" data-post-id="254827">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="tomkonidas" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/tomkonidas/120/22982_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  tomkonidas
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>We can even mix and match both solutions:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">def new(attrs) do
  __MODULE__
  |&gt; struct(attrs)
  |&gt; maybe_with_random_bytes()
end

defp maybe_with_random_bytes(%{bytes: nil} = struct) do
  Map.put(struct, :bytes, random_bytes())
end

defp maybe_with_random_bytes(struct), do: struct
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="254827" data-batch-url="/posts/batch_likers">
                        3
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/what-is-the-most-idiomatic-way-to-construct-structs-with-complex-default-values/48727/15">Post #14</a>
	                </div>
	            </div>
              <div id="likers-container-254827" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="254827"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #14"></div>
  </section>
</div>
    <div class="postbit" id="254838" data-post-id="254838">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="cjbottaro" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/cjbottaro/120/1469_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  cjbottaro
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group quote-modified" data-username="elt547" data-post="1" data-topic="48727">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/e/f6c823/48.png" class="avatar"> elt547:</div>
<blockquote>
<p>Someone suggested making a “new” function:</p>
<p>But to me this feels very non-idiomatic. It feels like shoehorning an object oriented pattern into a functional language.</p>
</blockquote>
</aside>
<p>I felt this way too until I divorced the word <code>new</code> from “object instantiation”.</p>
<p>I think the official Elixir documentation even says…</p>
<p>Just use data directly:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">%__MODULE__{email: email, bytes: random_bytes()}
</code></pre>
<p>If that’s not good enough, make a function:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">def new(email) do
  %__MODULE__{email: email, bytes: random_bytes()}
end
</code></pre>
<p>And finally… metaprogramming (no example… <img src="https://forum.elixirforum.com/images/emoji/apple/stuck_out_tongue.png?v=15" title=":stuck_out_tongue:" class="emoji" alt=":stuck_out_tongue:" loading="lazy" width="20" height="20">).</p>
<p>See the “In other words:” part of this section:</p><aside class="onebox allowlistedgeneric" data-onebox-src="https://elixir-lang.org/getting-started/meta/domain-specific-languages.html#foreword">
  <header class="source">

      <a href="https://elixir-lang.org/getting-started/meta/domain-specific-languages.html#foreword" target="_blank" rel="noopener nofollow">elixir-lang.org</a>
  </header>

  <article class="onebox-body">
    

<h3><a href="https://elixir-lang.org/getting-started/meta/domain-specific-languages.html#foreword" target="_blank" rel="noopener nofollow">Domain-Specific Languages (DSLs) — Elixir v1.20.2</a></h3>



  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>
 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="254838" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/what-is-the-most-idiomatic-way-to-construct-structs-with-complex-default-values/48727/16">Post #15</a>
	                </div>
	            </div>
              <div id="likers-container-254838" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="254838"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #15"></div>
  </section>
</div>
    <div class="postbit" id="254846" data-post-id="254846">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="al2o3cr" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/al2o3cr/120/3457_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  al2o3cr
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Quick note: 99% of the time when you write <code>struct</code> you really mean <a href="https://hexdocs.pm/elixir/Kernel.html#struct!/2" rel="nofollow"><code>struct!</code></a> because</p>
<ul>
<li><code>struct!</code> will raise if required keys from <code>@enforce_keys</code> are omitted</li>
<li><code>struct!</code> will raise if given keys that aren’t allowed in the struct</li>
</ul>
<hr>
<p>Another pattern that can catch bad keys at compile-time: use a struct literal combined with a function to apply defaults. Something like:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule SessionRequest do
  defstruct [:email, :random_bytes]

  def setup(%__MODULE__{} = session) do
    Map.put_new_lazy(session, :bytes, fn -&gt; random_bytes() end)
  end
end

# at the callsite:
session_request =
  %SessionRequest{
    email: some_email
  }
  |&gt; SessionRequest.setup()
</code></pre>
<p>This is a little over-abstracted for the case where <code>SessionRequest</code> only has one field supplied by the user, but would make more sense if there were a dozen:</p>
<ul>
<li>the compiler will catch invalid keys in the literal</li>
<li>if you’ve declared types for the specific keys, Dialyzer may catch errors like assigning a literal string to a key declared to be <code>integer()</code>. It will NOT catch misconfigured use of <code>struct</code>/<code>struct!</code></li>
</ul> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="254846" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/what-is-the-most-idiomatic-way-to-construct-structs-with-complex-default-values/48727/17">Post #16</a>
	                </div>
	            </div>
              <div id="likers-container-254846" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="254846"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #16"></div>
  </section>
</div>
    <div class="postbit" id="254848" data-post-id="254848">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="cjbottaro" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/cjbottaro/120/1469_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  cjbottaro
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I think the post is really about “struct default values that are determined at runtime”…</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule Foo
  defstruct [:email, bytes: &amp;random_bytes/0]

  defp random_bytes do
    :erlang.rand_bytes(16)
  end
end
</code></pre>
<p>Which admittedly would be kinda nice… <img src="https://forum.elixirforum.com/images/emoji/apple/slight_smile.png?v=15" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="254848" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/what-is-the-most-idiomatic-way-to-construct-structs-with-complex-default-values/48727/18">Post #17</a>
	                </div>
	            </div>
              <div id="likers-container-254848" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="254848"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #17"></div>
  </section>
</div>
    <div class="postbit" id="256819" data-post-id="256819">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="ycherniavskyi" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/ycherniavskyi/120/19559_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  ycherniavskyi
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Your example does not compile <img src="https://forum.elixirforum.com/images/emoji/apple/man_shrugging/2.png?v=15" title=":man_shrugging:t2:" class="emoji" alt=":man_shrugging:t2:" loading="lazy" width="20" height="20"> (I have fixed some compile errors already):</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">Erlang/OTP 25 [erts-13.0.2] [source] [64-bit] [smp:10:10] [ds:10:10:10] [async-threads:1] [jit] [dtrace]

Interactive Elixir (1.13.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)&gt; defmodule Foo do
...(1)&gt;   defstruct [:email, bytes: &amp;random_bytes/0]
...(1)&gt;
...(1)&gt;   defp random_bytes do
...(1)&gt;     :rand.uniform(100)
...(1)&gt;   end
...(1)&gt; end
** (CompileError) iex:2: undefined function random_bytes/0 (there is no such import)
    (elixir 1.13.4) expanding macro: Kernel.defstruct/1
iex(1)&gt;
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="256819" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/what-is-the-most-idiomatic-way-to-construct-structs-with-complex-default-values/48727/19">Post #18</a>
	                </div>
	            </div>
              <div id="likers-container-256819" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="256819"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #18"></div>
  </section>
</div>
    <div class="postbit" id="256834" data-post-id="256834">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="cjbottaro" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/cjbottaro/120/1469_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  cjbottaro
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I was trying to say “this is an example of what OP was asking for”. It doesn’t work, but it would be nice if it did.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="256834" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/what-is-the-most-idiomatic-way-to-construct-structs-with-complex-default-values/48727/20">Post #19</a>
	                </div>
	            </div>
              <div id="likers-container-256834" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="256834"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #19"></div>
  </section>
</div>
    <div class="postbit" id="256843" data-post-id="256843">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="sodapopcan" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/sodapopcan/120/34668_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  sodapopcan
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="cjbottaro" data-post="20" data-topic="48727">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/cjbottaro/48/1469_2.png" class="avatar"> cjbottaro:</div>
<blockquote>
<p>It doesn’t work, but it would be nice if it did.</p>
</blockquote>
</aside>
<p>I personally don’t think this would be nice as it would mean coming across a wild <code>%Foo{}</code> means there could be side-effects.  I’m perfectly happy with status quo where <code>%Foo{}</code> means “static thing I’m allow to manipulate” and <code>Foo.new()</code> means “I’m special, please let me construct myself!”.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="256843" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/what-is-the-most-idiomatic-way-to-construct-structs-with-complex-default-values/48727/21">Post #20</a>
	                </div>
	            </div>
              <div id="likers-container-256843" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="256843"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-last-post cat-last-post" title="Last post!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>