I have a custom json deserializer. It can parse string or number.

json functions return Result enum so I guess if it fails it should return
Err. But lines println!("crap") or println!("string is ok")  are not
reached.

Program crashes with the following output:

not int. let's try string
task '<main>' failed at 'called `Option::unwrap()` on a `None` value',
/home/rustbuild/src/rust-buildbot/slave/nightly-linux/build/src/libcore/
option.rs:278


extern crate serialize;
use serialize::{json, Decodable, Decoder};

fn main() {
    let raw_json = "\"ddd\"";
    let person: Primitive = json::decode(raw_json).unwrap();
    println!("{}", person);
}

#[deriving(Show)]
enum Primitive { ItInt(int), ItStr(String) }

impl<S: Decoder<E>, E> Decodable<S, E> for Primitive {
    fn decode(decoder: &mut S) -> Result<Primitive, E> {
        match decoder.read_int() {
            Ok(n) => Ok(ItInt(n)),
            _     => {
                println!("not int. let's try string");
                match decoder.read_str() {
                    Ok(s) => {
                        println!("string is ok");
                        Ok(ItStr(s))
                    },
                    _     => {
                        println!("crap");
                        Ok(ItStr("DDD".to_string()))
                    }
                }
            }
        }
    }
}

-- 
Daneel S. Yaitskov
_______________________________________________
Rust-dev mailing list
Rust-dev@mozilla.org
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to