-
Notifications
You must be signed in to change notification settings - Fork 217
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Custom Struct Encoding/Decoding #15
Comments
My guess is that your code is missing an import for the Note that you can implement impl<E, D: Decoder<E>> Decodable<D, E> for Rational {
fn decode(d: &mut D) -> Result<Rational, E> {
let field = try!(d.read_str());
match field.parse() {
Some(rat) => Ok(rat),
None => Err(d.error(&*format!(
"Could not parse '{}' as a rational.", field))),
}
}
}
For the most part, the For example, you're actually using a lot more than just let (x, y, r): (f64, f64, Rational) = row.unwrap(); in your #[deriving(RustcDecodable)]
struct Row {
x: f64,
y: f64,
rat: Rational,
} and decoded it like so: All of this is only made possible because of the automatic deriving implementations provided by the Finally, the CSV parsing and decoding are decoupled. You don't have to use the decoding infrastructure if you don't want to. You can just read This was a really phenomenal question, so I've added a fully working example to the repo. :-) |
Wow! Thank you for this amazing and very thorough answer; it is much appreciated :) Regarding the missing Thanks for demonstrating how to implement the Lastly, I'm glad you were able to adapt my question and make an example out of it :) |
No problem! Happy hacking! :-) |
Firstly, I am not sure whether this issue/question belongs here or over at rust-lang/rustc-serialize, but I think I should ask this here first.
I was wondering how one goes about telling CSV and/or serialize that a particular Struct is formatted a particular way. This is probably best illustrated with the following example:
This will compile fine, but it unsurprisingly results in the error
since it it expect two columns for
Rational
.I have tried to replace the
#[deriving(RustcDecodable)]
by implementing that trait manually; but I do not seem to be getting very far. This is my attempt so farbut for some reason, it seems that
read_str
is not implemented forcsv::Decoded
yet the documentation (and source) clearly show that it should be implemented. (It is getting late, so I am perhaps missing something obvious).Curiously, why does CSV use the
serialize
crate in order to parse the data? Why not simply useFromStr
? It would seem to me a lot more straightforward; especially since as far as I see it, the whole serialize crate is acting like a big and overly complicated wrapper for justFromStr
in this context.The text was updated successfully, but these errors were encountered: