Skip to content

Instantly share code, notes, and snippets.

@johnynek
Last active February 1, 2024 11:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save johnynek/092e2a9721d5e15f70b5aec4aec51eea to your computer and use it in GitHub Desktop.
Save johnynek/092e2a9721d5e15f70b5aec4aec51eea 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 <boykin@pobox.com>"]
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 {
match map.get_mut(&record.key) {
Some(v0) => {
*v0 += v;
},
None => {
map.insert(record.key, 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