title: How can I downcast a dyn trait into another trait in Rust?
body: <p>I have two Rust traits, and one automatically implements the other:</p>
  <pre><code>trait A {
    fn something(&amp;self);
  }
  trait B {}
  impl A for dyn B {
    fn something(&amp;self) {
      println!(&quot;hello from B&quot;)
    }
  }
  </code></pre>
  <p>Now I receive a dynamic implementation of <code>B</code>, and I need to return a dynamic implementation of <code>A</code>:</p>
  <pre><code>fn downcast(b: Box&lt;dyn B&gt;) -&gt; Box&lt;dyn A&gt; {...}
  </code></pre>
  <p><strong>How can I implement <code>downcast</code>?</strong></p>
  <p>Some things I've tried:</p>
  <ol>
  <li>I tried to let Rust figure it out statically:</li>
  </ol>
  <pre><code>fn downcast(b: Box&lt;dyn B&gt;) -&gt; Box&lt;dyn A&gt; {
    b
  }
  </code></pre>
  <p>This gives something like</p>
  <pre><code>error[E0308]: mismatched types
  expected trait `A`, found trait `B`
  </code></pre>
  <ol start="2">
  <li><p>I tried the same static thing using <code>as</code> or an intermediate variable.</p>
  </li>
  <li><p>I tried dynamically casting using <code>Any</code> and <code>downcast_ref</code>, but I couldn't get the magic right.</p>
  </li>
  </ol>