Those kinds of errors are made trivial to handle with ? and anyhow. At least, once you’ve got a bit of practice with it. And it’s barely slower to write out; 1 character in most cases, and “Result<>” on your return type.
I ported some random Python to Rust six months ago: https://news.ycombinator.com/item?id=22712441 Here's the version I'd write today:
use anyhow::Result;
use chrono::NaiveDateTime;
use serde::Deserialize;
use serde_json;
#[derive(Deserialize)]
struct Person {
name: String,
age: u32,
hired: NaiveDateTime,
emails: Vec<String>,
}
fn main() -> Result<()> {
let data = std::fs::read_to_string("agenda.json")?;
let mut people: Vec<Person> = serde_json::from_str(&data)?;
people.sort_by(|a, b| b.name.cmp(&a.name));
for person in &people {
println!("{} ({}) - {}", person.name, person.age, person.hired);
for email in &person.emails {
println!(" - {}", email);
}
}
Ok(())
}
I learned that Chrono supports serde so I can remove my own parsing, and using ? instead of unwrap, because it's not harder and it ends up being nicer overall.(EDIT: Ah actually, it won't recognize this specific format automatically, so I still would write the parsing code. Even then, it's still roughly in the same ballpark.)