blfuentes
blfuentes

Reputation: 2827

Read lines in Rust with match result

I'm pretty new with Rust and trying to implement some basic stuff. So one of the samples from the doc is about reading lines from a text file: https://doc.rust-lang.org/rust-by-example/std_misc/file/read_lines.html

The sample code works (obviously...) but I wanted to modify it to add some error handling but the compiler complains about the result I define

// the result after -> is not valid...
pub fn read_lines<P>(filename: P) -> std::result::Result<std::io::Lines<std::io::BufReader<std::fs::File>>, std::io::Error>
where P: AsRef<Path>, {
    let file = File::open(filename);
    let file = match file {
        Ok(file) => io::BufReader::new(file).lines(),
        Err(error) => panic!("Problem opening the file: {:?}", error),
    };
}

// this is fine
pub fn read_lines2<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
    let file = File::open(filename)?;
    Ok(io::BufReader::new(file).lines())
}

I've tried different suggestions from the intellisense but no luck.

Any idea about how to define the result when there is an Ok/Err ?

Upvotes: 0

Views: 1180

Answers (2)

Coder-256
Coder-256

Reputation: 5618

If I understand the intent of your code correctly, here is a more canonical version:

use std::fs::File;
use std::io::{self, prelude::*};
use std::path::Path;

pub fn read_lines(filename: &Path) -> io::Lines<io::BufReader<File>> {
    let file = File::open(filename).expect("Problem opening the file");
    io::BufReader::new(file).lines()
}

If you want the caller to handle any errors, return something like io::Result<T> (an alias for std::result::Result<T, io::Error>), indicating a possible failure. However, if you decide to handle the error inside the function using something like panic!() or Result::expect(), then there is no need to return a Result to the caller since the function only returns to the caller if no error occurred.

Upvotes: 1

hkBst
hkBst

Reputation: 3380

Is this what you were looking for?

pub fn read_lines<P>(filename: P) -> std::result::Result<std::io::Lines<std::io::BufReader<std::fs::File>>, std::io::Error>
where P: AsRef<Path>, {
    let file = File::open(filename);
    match file {
        Ok(file) => Ok(io::BufReader::new(file).lines()),
        Err(error) => panic!("Problem opening the file: {:?}", error),
    }
}

I removed the let file = and ; to enable implicit return, and added an Ok() wrapper around the happy path.

Upvotes: 1

Related Questions