Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::fs::File;
- use std::io::{BufRead, BufReader};
- fn main() {
- println!("Hello, world!");
- // this is a shorter way of writing your `match` loop. It gives you your
- // `Vec<i64>` on success or panics with an error message if the function
- // fails at opening the file or parsing its contents
- let something = read("temp.txt").unwrap();
- println!("{:?}", something);
- }
- // function takes path in the form of string slice and returns enum
- // which contains vector of integers on success or an error.
- // The use of `dyn std::error::Error` means this function is capable of
- // dynamically returning multiple kinds of errors.
- fn read(path: &str) -> Result<Vec<i64>, Box<dyn std::error::Error>> {
- println!("Entered Read Function");
- let file = File::open(path)?; // open file by given path
- let br = BufReader::new(file);
- let mut v = Vec::new();
- for line in br.lines() {
- // The `lines()` iterator needs to perform IO to read from the file, and
- // your code has to know what to do if reading from the file ever fails.
- // This code gives you a `&str` representing the contents of the line if
- // reading from the file succeeds, or returns an `io::Error` otherwise.
- let line = line?;
- for s in line.split_whitespace() {
- // this parses each `&str` into an `i64` if it succeeds or returns
- // a `ParseIntError` if it fails
- let s = s.parse()?;
- v.push(s);
- }
- }
- Ok(v) // everything is Ok, return vector
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement