Skip to content

Instantly share code, notes, and snippets.

@RoxasShadow
Last active August 29, 2015 14:21
Show Gist options
  • Save RoxasShadow/7eb0395f589122418f59 to your computer and use it in GitHub Desktop.
Save RoxasShadow/7eb0395f589122418f59 to your computer and use it in GitHub Desktop.
Notes about rust (pretty much nothing you can find on the book or just googling, but can be useful...)

#1

fn get_results() -> Option<Json> {
  // ...
  let json = &Json::from_str(&body).unwrap();

  return match json.as_object().unwrap().get("results") {
    Some(obj) => Some(obj.clone()),
    _ => None
  }
}
  1. We cannot return json.as_object().unwrap().get("results") since it's a Option<&Json>
  2. The way above is derp

Solution:

let json = &Json::from_str(&body).unwrap();

return json.as_object().unwrap()
  .get("results").map(|r| r.clone());

#2

If you need (de)serialization (both json and xml), use the rustc-serialize crate.

#3

Push on (de)serializing data using structs. Decodable works even with structs containing other collections of structs

#4

rust-lang-deprecated/rustc-serialize#112

#5

CLI's args are 0-indexed ([0] is the executable's path), so you need to check if args().collect().len() > 1

#6

Decoder is smart enough to match the nearest json fields with the respective given string.

decoder.read_struct("root", 0, |decoder| {
  Ok(Image {
    size: try!(decoder.read_struct_field("size",  0, |decoder| Decodable::decode(decoder))),
    url:  try!(decoder.read_struct_field("#text", 0, |decoder| Decodable::decode(decoder)))
  })
})

The code above works fine even if size and #text are nested from the root.

#7

If you want to share your macros through the modules, put them in macros.rs and import it before any other module with

#[macro_use]
mod macros

#8

decoder.read_struct_field("size",  0, |decoder| Decodable::decode(decoder)

is the same of

decoder.read_struct_field("size",  0, Decodable::decode

#9

https://gist.github.com/huonw/8435502

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment