Skip to content

Instantly share code, notes, and snippets.

@pmagwene
Created January 9, 2020 19:20
Show Gist options
  • Save pmagwene/f8680f02a48476c7e05bceabfb55dfcf to your computer and use it in GitHub Desktop.
Save pmagwene/f8680f02a48476c7e05bceabfb55dfcf to your computer and use it in GitHub Desktop.
Rust string references allowed
use std::error::Error;
use std::io::{BufRead, BufReader};
#[derive(Debug)]
struct Record<'a> {
line: &'a str,
words: Vec<&'a str>,
}
impl<'a> Record<'a> {
fn new() -> Record<'a> {
Record {
line: "",
words: Vec::new(),
}
}
fn parse(s: &'a str) -> Record<'a> {
let mut r = Record::new();
r.line = s;
r.words = r.line.split_whitespace().collect();
r
}
}
fn main() -> Result<(), Box<dyn Error>> {
let s = r#"
’Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
"#;
let mut records: Vec<Record> = Vec::new();
let rdr = BufReader::new(s.as_bytes());
let all_lines: Vec<String> = rdr.lines().filter_map(Result::ok).collect();
for line in &all_lines {
records.push(Record::parse(line));
}
println!("Number of records: {}", records.len());
let numwords: usize = records.iter().map(|r| r.words.len()).sum();
println!("Number of words: {}", numwords);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment