title: How do I deal with wrapper type invariance in Rust?
body: <p>References to wrapper types like <code>&amp;Rc&lt;T&gt;</code> and <code>&amp;Box&lt;T&gt;</code> are invariant in <code>T</code> (<code>&amp;Rc&lt;T&gt;</code> is not a <code>&amp;Rc&lt;U&gt;</code> even if <code>T</code> is a <code>U</code>). A concrete example of the issue (<a href="https://play.rust-lang.org/?code=use%20std%3A%3Arc%3A%3ARc%3B%0Ause%20std%3A%3Arc%3A%3AWeak%3B%0A%0Atrait%20MyTrait%20%7B%7D%0A%0Astruct%20MyStruct%20%7B%0A%7D%0A%0Aimpl%20MyTrait%20for%20MyStruct%20%7B%7D%0A%0Afn%20foo(rc_trait%3A%20Weak%3CMyTrait%3E)%20%7B%7D%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20a%20%3D%20Rc%3A%3Anew(MyStruct%20%7B%7D)%3B%0A%20%20%20%20foo(Rc%3A%3Adowngrade(%26a))%3B%0A%7D%0A&amp;version=stable&amp;backtrace=0">Rust Playground</a>):</p>
  
  <pre><code>use std::rc::Rc;
  use std::rc::Weak;
  
  trait MyTrait {}
  
  struct MyStruct {
  }
  
  impl MyTrait for MyStruct {}
  
  fn foo(rc_trait: Weak&lt;MyTrait&gt;) {}
  
  fn main() {
      let a = Rc::new(MyStruct {});
      foo(Rc::downgrade(&amp;a));
  }
  </code></pre>
  
  <p>This code results in the following error:</p>
  
  <pre><code>&lt;anon&gt;:15:23: 15:25 error: mismatched types:
   expected `&amp;alloc::rc::Rc&lt;MyTrait&gt;`,
      found `&amp;alloc::rc::Rc&lt;MyStruct&gt;`
  </code></pre>
  
  <p>Similar example (with similar error) with <code>Box&lt;T&gt;</code> (<a href="https://play.rust-lang.org/?code=trait%20MyTrait%20%7B%7D%0A%0Astruct%20MyStruct%20%7B%0A%7D%0A%0Aimpl%20MyTrait%20for%20MyStruct%20%7B%7D%0A%0Afn%20foo(rc_trait%3A%20%26Box%3CMyTrait%3E)%20%7B%7D%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20a%20%3D%20Box%3A%3Anew(MyStruct%20%7B%7D)%3B%0A%20%20%20%20foo(%26a)%3B%0A%7D%0A&amp;version=stable&amp;backtrace=0">Rust Playground</a>):</p>
  
  <pre><code>trait MyTrait {}
  
  struct MyStruct {
  }
  
  impl MyTrait for MyStruct {}
  
  fn foo(rc_trait: &amp;Box&lt;MyTrait&gt;) {}
  
  fn main() {
      let a = Box::new(MyStruct {});
      foo(&amp;a);
  }
  </code></pre>
  
  <p>In these cases I could of course just annotate <code>a</code> with the desired type, but in many cases that won't be possible because the original type is needed as well. So what do I do then?</p>