Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. use std::fs::File;
  2. use std::io::{BufRead, BufReader};
  3.  
  4. fn main() {
  5. println!("Hello, world!");
  6.  
  7. // this is a shorter way of writing your `match` loop. It gives you your
  8. // `Vec<i64>` on success or panics with an error message if the function
  9. // fails at opening the file or parsing its contents
  10. let something = read("temp.txt").unwrap();
  11.  
  12. println!("{:?}", something);
  13. }
  14.  
  15. // function takes path in the form of string slice and returns enum
  16. // which contains vector of integers on success or an error.
  17.  
  18. // The use of `dyn std::error::Error` means this function is capable of
  19. // dynamically returning multiple kinds of errors.
  20. fn read(path: &str) -> Result<Vec<i64>, Box<dyn std::error::Error>> {
  21. println!("Entered Read Function");
  22. let file = File::open(path)?; // open file by given path
  23.  
  24. let br = BufReader::new(file);
  25.  
  26. let mut v = Vec::new();
  27.  
  28. for line in br.lines() {
  29. // The `lines()` iterator needs to perform IO to read from the file,
  30. // and your code has to know what to do if reading from the file ever fails.
  31. // This code gives you a `&str` representing the contents of the line
  32. // if reading from the file succeeds, or returns an `io::Error` if it doesn't
  33. let line = line?;
  34.  
  35. for s in line.split_whitespace() {
  36. // this parses each `&str` into an `i64` if it succeeds or returns
  37. // a `ParseIntError` if it fails
  38. let s = s.parse()?;
  39. v.push(s);
  40. }
  41. }
  42. Ok(v) // everything is Ok, return vector
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement