I am attempting to return an error from Serde with a function that returns Result<(), Error>:
use std::io::{Error};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Mine {
ab: u8,
ac: u8,
}
#[macro_use]
extern crate serde_derive;
fn main() {
if do_match().is_ok() {
println!("Success");
}
}
fn do_match() -> Result<(), Error> {
match serde_json::from_str::<Mine>("test") {
Ok(_e) => println!("Okay"),
Err(e) => return e,
}
Ok(())
}
After various attempts, I have been unable to correct the problem to return an error, how can I do this?
Firstly, you are using the wrong error type.
serde_json::from_str'sErris of typeserde_json::error::Errorwhereas you are usingstd::io::Error. Secondly, by pattern matching onErr(e)and then trying toreturn e, you are no longer return aResultbut instead trying to just return something of typeserde_json::error::Error. Instead, you should be returningResult<(), serde_json::error::Error>. Here is the proper way to accomplish what you are trying to achieve:mapwill only perform theprintln!(...)on the result fromserde_json::from_strif it is anOkvariant, otherwise, it will just pass through theErrvariant. Then, you can just return the resulting expression.Rust Playground