Skip to content

Instantly share code, notes, and snippets.

@stew
Forked from johnynek/Cargo.toml
Last active July 19, 2020 03:31
Show Gist options
  • Save stew/65dcbb343625d5adad32ceeb264310aa to your computer and use it in GitHub Desktop.
Save stew/65dcbb343625d5adad32ceeb264310aa to your computer and use it in GitHub Desktop.
a toy example of CSV wordcount.
[package]
name = "hello"
version = "0.1.0"
authors = ["P. Oscar Boykin <[email protected]>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
csv = "1.1"
serde = { version = "1.0.114", features = ["derive"] }
~
use std::error::Error;
use std::io;
use std::process;
use std::collections::HashMap;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Record {
key: String,
value: Option<i64>,
}
fn example() -> Result<(), Box<dyn Error>> {
let mut map: HashMap<String, i64> = HashMap::new();
let mut rdr = csv::Reader::from_reader(io::stdin());
for result in rdr.deserialize() {
// Notice that we need to provide a type hint for automatic
// deserialization.
let record: Record = result?;
if let Some(v) = record.value {
let r = map.entry(record.key).or_insert(0);
*r += v;
}
}
println!("{:?}", map);
Ok(())
}
fn main() {
if let Err(err) = example() {
println!("error running example: {}", err);
process::exit(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment