[rust-dev] Expected fields in traits

Tommi rusty.gates at icloud.com
Thu Apr 17 06:01:08 PDT 2014


On 2014-04-17, at 11:25, Marvin Löbel <loebel.marvin at gmail.com> wrote:

> Would you mind me taking this RFC over and including it into my proposal?

Yes please, by all means. I'm looking forward to your proposal.

But actually I just realized that my proposal is essentially just a syntax sugar for a macro producing boiler-plate code. That imaginary macro simply copy pastes the provided method defined in the trait to the trait implementation and replaces each use of an expected field with the actual field that's mapped to it. So, in some sense you could simply think of my example 1 (the one with the imaginary syntax) translating to this (actual Rust code):

trait Unify<T: Clone> {
   fn unify(&mut self);
}

struct Stuff {
   a: u32,
   b: u32
}

impl Unify<u32> for Stuff {
   fn unify(&mut self) {
       self.b = self.a.clone();
   }
}

And here's that example 1 again for completeness sake:

trait Unify<T: Clone> {
   Self {
       x: T,
       y: T
   }

   fn unify(&mut self) {
       self.y = self.x.clone();
   }
}

struct Stuff {
   a: u32,
   b: u32
}

impl Unify<u32> for Stuff {
   Stuff {
       x => a,
       y => b
   }
}

But a small and important detail about the compiler implementation is that if there are multiple types that implement Unify<u32> with the exactly same field offsets for the expected fields, then the compiler can compile the function Unify<u32>::unify for those types just once and use the same function for each type.

A simple textual macro with a search & replace is very easy to reason about.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140417/055c9d2f/attachment.html>


More information about the Rust-dev mailing list