[rust-dev] Understanding extra::{Encodable, Encoder}

Neil LoBracco niceguyneil at gmail.com
Sat Jan 25 09:22:53 PST 2014

Hey guys,
I'm getting started with Rust, building out a web services framework.
I have an enum methods can return for their response body:
public enum ResponseBody {

As you may know, this doesn't work, because Encodable expects a type
parameter for Encoder. This is needed because Encodable has method:
fn encode<http://static.rust-lang.org/doc/master/extra/serialize/trait.Encodable.html#tymethod.encode>(&self,
s: &mut S);
I can't even say JSON(~serialize::Encodable<json::Encoder>), because
json::Encoder has a lifetime param that comes from its writer!
It seems like this makes it impossible to ever take in a serializable
object, and serialize it however I fancy. Moreover, it seems odd for the
Encodable to know what it's encoded into - all of the logic that goes into
actually turning an object into json/xml/whatever lives in json::Encoder,
etc, so why should the Encodable be coupled with that?
What makes sense to me would be to be able to say:
pub fn stringify(obj : &Encodable) -> ~str {
  let reader = json::Encoder::new(obj);
Where the Encoder trait implies the Reader trait. If something were
Encodable, that would not be specific to any particular Encoder - it would
be a general statement.

Anyone have thoughts about this? Am I missing any easy way I would be able
to do what I asked above (take in a ~Encodable and encode it to buffer,
without having whoever created the encodable have to know about the writer
that would eventually get used)?
If we want to make changes here, I can certainly help out with that, just
wanted to understand what's going on here and the rationale.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140125/16592b46/attachment.html>

More information about the Rust-dev mailing list