[RESOLVED] Serde error when deserializing (type annotation)


#1

Hey everyone,

I am trying to make a simple web server in rust to make a backend and replace PHP for my own projects.
This is mostly for fun and to learn more about Rust since it is a language that I really find fascinating. I want to learn more about it and learn how to really use it.

I am having an issue with those lines of code:

let resp: JsonResponse = match serde_json::from_str(&payload) {
    Ok(data) => {
        JsonResponse::success("Success".to_string())
    },
    Err(e) => {
        JsonResponse::error("Error".to_string())
    }
};

payload is a String. And JsonResponse is a simple struct with an implementation that returns me what I want/need.
At Ok(data), it says error 282| type annotations needed.
I do not understand this error at all. Am I doing something wrong ?

I am basing myself on this little tutorial

Thank you in advance!

EDIT:
The way around this issue is to explicitly cast the object when it enters the Ok statement:

let json_data: JsonData = data;

This works, but I want to know if this is the right way to do it ?


#2

If you look at the signature of from_str you’ll see that it takes a generic type parameter T. That’s the type it’ll try to deserialize into. Note also that the caller (you) indicate the type here. How does it know which type to use? Most Rust code will rely on compiler’s type inference to deduce the type. How does the compiler know? It looks at how you’re using the type, particularly what it’s being assigned to (or passed to functions) - if those nail down the type unambiguously then all’s well. When it can’t glean this information from usage, it’ll ask you to provide a type annotation. That’s what happens here.

Since you don’t make use of data, it cannot infer the type you want. You have a few options:

  1. Specify the T explicitly in from_str: from_str::<JsonData>(&payload)
  2. Specify the type in the Ok arm: Ok::<JsonData>(data)
  3. Use the data somehow such that the type becomes known. Your binding let json_data: JsonData = data is one example.

#1 is what most Rust code would choose in this case.


#3

Well, I found the #3 alone by reading on some other issues and code.
I will use #1 if it’s the go to way. I tried some things that were like this but didn’t add “::” after from_str.
This language isn’t that easy to learn. I love it :stuck_out_tongue:

Thank you very much for this answer !