How to match serde error?

I'm deserializing JSON with serde:

use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct MyType {
    a: String
}

fn main() {
    let m: MyType = serde_json::from_str("{\"a\":\"b\"}").unwrap();
    println!("{:#?}", m);
}

Now instead of unwrap() I would like to match the Result. Something like:

    match serde_json::from_str("{\"a\":\"b\"}") {
        Ok(m: MyType) => { println!("{:#?}", m) },
        Err(e) => { println!("{:#?}", e) }
    }

Ok(m: MyType) is not valid syntax.

Where should I put the MyType?

match serde_json::from_str::<MyType>("{\"a\":\"b\"}") {
    Ok(m) => { println!("{:#?}", m) },
    Err(e) => { println!("{:#?}", e) }
}
2 Likes

Wow. How? Ah, of course, json<T>() returns Result<T> and only the T goes into the turbofish.

In case it isn’t clear why this works. Looking into the docs:

pub fn from_str<'a, T>(s: &'a str) -> Result<T> 
where
    T: Deserialize<'a>, 

The serde_json::from_str has a type parameter T. This parameter can be passed explicitly. Giving MyType for T makes from_str return Result<MyType> (where Result is a synonym type Result<T> = std::result::Result<T, serde_json::Error>;).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.