Reputation: 2527
The following Rust program works fine using cargo run
on cargo 1.39.0-nightly:
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
use serde_json::Value as JsonValue;
#[derive(Serialize,Deserialize)]
struct JData
{
names: Vec<String>
}
fn main() {
let json_str = r#"
{
"names": ["James", "Carl", "Megan"]
}
"#;
let res = serde_json::from_str(json_str); // res is Result
if res.is_ok()
{
let p: JData = res.unwrap();
println!("{}", p.names[1]);
}
else
{
eprintln!("Sorry, couldn't parse JSON :(");
}
}
However, if I change the line names: Vec<String>
to names: Vec<u8>
it fails with this error:
Sorry, couldn't parse JSON :(
Understandbly, this program should fail. But I don't understand why it reaches this line since this error is displayed as a result of let res = serde_json::from_str(json_str);
which has nothing to do with the let p: JData = res.unwrap();
step of the program. In other words, the from_str()
line has no dependency on the subsequent try to parse into JData struct line, yet the error indicates that the from_str()
line failed, not that it could not parse into JData
.
Upvotes: 2
Views: 213
Reputation: 6698
The type of res
is determined by the let p: JData
at compile time, even if control never reaches that line at runtime. That type, Result<JData, …>
, controls the behavior of serde_json::from_str
, which causes it to fail at reading string literals in to u8
s.
Upvotes: 3