Thanks for the quick response, Steven! Having done what you suggested, I'm now getting the following error (for serializing a larger struct in which some fields are strings):
impl<T: Writer> MySerialization for T { fn write_my_string(&mut self, s: &str) -> IoResult<()> { ... } } impl StructToBeSerialized { fn save_to(&self, writer: &mut io::Writer) -> io::IoResult<()> { try!(writer.write_my_string(self.string_field_1)); // error at this line } } The error is at the indicated line and it says: cannot borrow immutable argument `writer` as mutable. However, the function argument writer to save_to is a &mut io::Writer, which would seem to be mutable to me. Would you happen to know what's going wrong with this code? Thanks again! Frank On Sat, Apr 5, 2014 at 1:17 PM, Steven Fackler <sfack...@gmail.com> wrote: > 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