title: How do boxed traits interact with memory when using match in Rust?
body: <p>I have the following function:</p>
  <pre class="lang-rust prettyprint-override"><code>fn get_person(type: PersonType, age: u8) -&gt; Result&lt;Box&lt;dyn Person&gt;&gt; {
      Ok(match type {
          PersonType::Thin =&gt; Box::new(ThinPerson::new(age)),
          PersonType::Fat =&gt; Box::new(FatPerson::new(age)),
      })
  }
  </code></pre>
  <p>Let's assume <code>ThinPerson</code> and <code>FatPerson</code> both implement <code>Person</code> trait. And <code>FatPerson</code> struct requires a much larger memory footprint.</p>
  <p>I believe during <code>Box::new(...)</code>, <code>ThinPerson</code>/<code>FatPerson</code> structs are first created on the stack and then <em>pushed off</em> into the heap once boxed.</p>
  <p>Initially, I had only <code>ThinPerson</code> as an arm to the <code>match</code>. Once I added <code>FatPerson</code>, I noticed the stack usage has increased even if the code never traverses the <code>PersonType::Fat</code> arm.</p>
  <p>Can someone please explain why? Does the <code>match</code> somehow looks at <em>all</em> the arms and allocates stack space according to the largest struct it finds?</p>
  <p>As a secondary question, how would I avoid this stack bloat? I understand &quot;placement by return&quot; RFC is still in the design phase and I cannot step outside safe Rust.</p>