You can do it like this:

impl<T: Writer> MySerialization for T {
    ...
}

Steven Fackler


On Sat, Apr 5, 2014 at 12:57 PM, Frank Huang <m...@nongraphical.com> wrote:

> Hello everyone,
>
> I have a question about making "extension methods" on something like
> io::Writer. Basically, I have a data format that requires strings to be
> serialized as an 8-byte length header and then the string bytes themselves.
> Instead of having to type writer.write_u64(...); writer.write_str(...);
> over and over again, I would like to implement some "extension methods" or
> something like that on io::Writer, like the following pseudocode:
>
> trait MySerialization {
>   fn write_my_string(&mut self, s: &str) -> io::IoResult<()>;
> }
>
> impl MySerialization for io::Writer {
>   fn write_my_string(&mut self, s: &str) -> io::IoResult<()> {
>     try!(self.write_u64(s.len());
>     self.write_str(s);
>   }
> }
>
> However, this of course doesn't work, because I can't implement a trait
> for a trait. Rustc says: "reference to trait `io::Writer` where a type is
> expected; try `@io::Writer`, `~io::Writer`, or `&io::Writer`", however when
> I try "&io::Writer" as suggested, rustc complains about lifetimes. Is this
> sort of thing possible in Rust?
>
> Thanks for your help!
> - Frank
>
> _______________________________________________
> Rust-dev mailing list
> Rust-dev@mozilla.org
> https://mail.mozilla.org/listinfo/rust-dev
>
>
_______________________________________________
Rust-dev mailing list
Rust-dev@mozilla.org
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to