title: How do I return an instance of a trait from a method?
body: <p>I'm trying to create a function that returns an instance of the <code>Shader</code> trait. Here is my drastically simplified code:</p>
  
  <pre><code>trait Shader {}
  
  struct MyShader;
  impl Shader for MyShader {}
  
  struct GraphicsContext;
  
  impl GraphicsContext {
      fn create_shader(&amp;self) -&gt; Shader {
          let shader = MyShader;
          shader
      }
  }
  
  fn main() {}
  </code></pre>
  
  <p>However I receive the following error:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0277]: the trait bound `Shader + 'static: std::marker::Sized` is not satisfied
    --&gt; src/main.rs:10:32
     |
  10 |     fn create_shader(&amp;self) -&gt; Shader {
     |                                ^^^^^^ `Shader + 'static` does not have a constant size known at compile-time
     |
     = help: the trait `std::marker::Sized` is not implemented for `Shader + 'static`
     = note: the return type of a function must have a statically known size
  </code></pre>
  
  <p>Newer versions of the compiler have this error:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0277]: the size for values of type `(dyn Shader + 'static)` cannot be known at compilation time
   --&gt; src/main.rs:9:32
    |
  9 |     fn create_shader(&amp;self) -&gt; Shader {
    |                                ^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `(dyn Shader + 'static)`
    = note: to learn more, visit &lt;https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait&gt;
    = note: the return type of a function must have a statically known size
  </code></pre>
  
  <p>This makes sense as the compiler doesn't know the size of the trait, but nowhere can I find the recommended way of fixing this.
  Passing back a reference with <code>&amp;</code> wouldn't work as far as I know because the reference would outlive the lifetime of its creator.</p>
  
  <p>Perhaps I need to use <code>Box&lt;T&gt;</code>?</p>