-
-
Save stew/65dcbb343625d5adad32ceeb264310aa to your computer and use it in GitHub Desktop.
a toy example of CSV wordcount.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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"] } | |
~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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