title: References to traits in structs
body: <p>I have a trait <code>Foo</code></p>
  
  <pre><code>pub trait Foo {
     fn do_something(&amp;self) -&gt; f64;
  }
  </code></pre>
  
  <p>and a struct which references that trait</p>
  
  <pre><code>pub struct Bar {
     foo: Foo,
  }
  </code></pre>
  
  <p>Trying to compile I get</p>
  
  <pre class="lang-none prettyprint-override"><code>error: reference to trait `Foo` where a type is expected; try `Box&lt;Foo&gt;` or `&amp;Foo`
  </code></pre>
  
  <p>Changing the struct to</p>
  
  <pre><code>struct Bar {
     foo: &amp;Foo,
  }
  </code></pre>
  
  <p>Tells me <code>error: missing lifetime specifier</code></p>
  
  <p>Changing the definition to</p>
  
  <pre><code>struct Bar {
     foo: Box&lt;Foo&gt;,
  }
  </code></pre>
  
  <p>Compiles — yay!</p>
  
  <p>However, when I want a function to return <code>foo</code> on <code>bar</code> - something like:</p>
  
  <pre><code>impl Bar {
      fn get_foo(&amp;self) -&gt; Foo {
          self.foo
      }
  }
  </code></pre>
  
  <p>Well obviously <code>bar.foo</code> is a <code>Box&lt;Foo&gt;</code>, so expectedly I get <code>error: reference to trait `Foo` where a type is expected; try `Box&lt;Foo&gt;` or `&amp;Foo`</code></p>
  
  <p>Changing the signature to</p>
  
  <pre><code>impl Bar {
      fn get_foo(&amp;self) -&gt; Box&lt;Foo&gt; {
          let this = *self;
          this.foo
      }
  }
  </code></pre>
  
  <p>But now I get <code>error: cannot move out of dereference of `&amp;`-pointer</code> on trying to dereference <code>self</code>.</p>
  
  <p>Changing to</p>
  
  <pre><code>impl Bar {
      fn get_foo(self) -&gt; Box&lt;Foo&gt; {
          self.foo
      }
  }
  </code></pre>
  
  <p>Is all good.</p>
  
  <p>So....</p>
  
  <ol>
  <li>Why doesn't <code>&amp;</code> in the <code>bar</code> struct work? I'm assuming I have to box
  as structs have a set memory layout so we have to say it's a pointer
  to a trait (as we can't know how big that will be), but why does the
  compiler suggest something that wont compile?</li>
  <li>Why can't I dereference <code>self</code> in <code>get_foo()</code> - All examples I've seen use the borrowed <code>self</code> syntax?</li>
  <li>What's the implication of removing the <code>&amp;</code> and just using <code>self</code>?</li>
  </ol>
  
  <p>Learning Rust is fascinating, but the memory safety is both fascinating and intimidating!</p>
  
  <p>Code in full that compiles:</p>
  
  <pre><code>trait Foo {
      fn do_something(&amp;self) -&gt; f64;
  }
  
  struct Bar {
      foo: Box&lt;Foo&gt;,
  }
  
  impl Bar {
      fn get_foo(self) -&gt; Box&lt;Foo&gt; {
          let foo = self.foo;
          foo.do_something();
          foo
      }
  }
  
  fn main() {}
  </code></pre>