title: Why would I implement methods on a trait instead of as part of the trait?
body: <p>While trying to understand the <code>Any</code> trait better, I saw that it <a href="https://github.com/rust-lang/rust/blob/1.31.1/src/libcore/any.rs#L146" rel="noreferrer">has an <code>impl</code> block for the trait itself</a>. I don't understand the purpose of this construct, or even if it has a specific name.</p>
  
  <p>I made a little experiment with both a "normal" trait method and a method defined in the <code>impl</code> block:</p>
  
  <pre><code>trait Foo {
      fn foo_in_trait(&amp;self) {
          println!("in foo")
      }
  }
  
  impl dyn Foo {
      fn foo_in_impl(&amp;self) {
          println!("in impl")
      }
  }
  
  impl Foo for u8 {}
  
  fn main() {
      let x = Box::new(42u8) as Box&lt;dyn Foo&gt;;
      x.foo_in_trait();
      x.foo_in_impl();
  
      let y = &amp;42u8 as &amp;dyn Foo;
      y.foo_in_trait();
      y.foo_in_impl(); // May cause an error, see below
  }
  </code></pre>
  
  <blockquote>
    <p><strong>Editor's note</strong></p>
    
    <p>In versions of Rust up to and including Rust 1.15.0, the line
    <code>y.foo_in_impl()</code> causes the error:</p>
    
    <pre class="lang-none prettyprint-override"><code>error: borrowed value does not live long enough
    --&gt; src/main.rs:20:14
     |
  20 |     let y = &amp;42u8 as &amp;Foo;
     |              ^^^^ does not live long enough
  ...
  23 | }
     | - temporary value only lives until here
     |
     = note: borrowed value must be valid for the static lifetime...
  </code></pre>
    
    <p>This error is no longer present in subsequent versions, but the
    concepts explained in the answers are still valid.</p>
  </blockquote>
  
  <p>From this limited experiment, it seems like methods defined in the <code>impl</code> block are more restrictive than methods defined in the <code>trait</code> block. It's likely that there's something extra that doing it this way unlocks, but I just don't know what it is yet! ^_^</p>
  
  <p>The sections from <em>The Rust Programming Language</em> on <a href="https://doc.rust-lang.org/stable/book/ch10-02-traits.html" rel="noreferrer">traits</a> and <a href="https://doc.rust-lang.org/stable/book/ch17-02-trait-objects.html" rel="noreferrer">trait objects</a> don't make any mention of this. Searching the Rust source itself, it seems like only <code>Any</code> and <a href="https://doc.rust-lang.org/std/error/trait.Error.html" rel="noreferrer"><code>Error</code></a> use this particular feature. I've not seen this used in the handful of crates where I have looked at the source code.</p>