Created
January 9, 2020 19:20
-
-
Save pmagwene/f8680f02a48476c7e05bceabfb55dfcf to your computer and use it in GitHub Desktop.
Rust string references allowed
This file contains hidden or 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::{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