Skip to content

Instantly share code, notes, and snippets.

@brendanzab
Forked from Aatch/borrow-example.rs
Created March 31, 2014 06:37
Show Gist options
  • Save brendanzab/9886521 to your computer and use it in GitHub Desktop.
Save brendanzab/9886521 to your computer and use it in GitHub Desktop.
extern crate serialize;
use serialize::json;
fn get_string<'a>(data: &'a json::Json, key: &~str) -> Option<&'a str> {
match *data {
json::Object(ref map) => {
match map.find(key) {
Some(&json::String(ref s)) => {
Some(s.as_slice())
},
_ => None,
}
},
_ => None,
}
}
fn main() {
let data = json::from_str(stringify!(
{
"language": "Rust",
"level" : 9001
}
)).unwrap();
println!("{}", get_string(&data, &~"language")); // Prints Some("Rust")
println!("{}", get_string(&data, &~"level")); // Prints None
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment