Created
January 9, 2020 19:20
-
-
Save pmagwene/91ba2e81e1488c091211a45f27f962a1 to your computer and use it in GitHub Desktop.
Rust references dis-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 | |
} | |
} | |
struct Table<'a> { | |
records: Vec<Record<'a>>, | |
} | |
impl<'a> Table<'a> { | |
fn parse(rdr: impl BufRead) -> Table<'a> { | |
let mut records: Vec<Record> = Vec::new(); | |
let all_lines: Vec<String> = rdr.lines().filter_map(Result::ok).collect(); | |
for line in &all_lines { | |
records.push(Record::parse(line)); | |
} | |
Table { records } | |
} | |
} | |
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 rdr = BufReader::new(s.as_bytes()); | |
let tbl = Table::parse(rdr); | |
println!("Number of records: {}", tbl.records.len()); | |
let numwords: usize = tbl.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