Please consider this:
#1 with collect()
use anyhow::{Context, Result};
#[allow(unused_imports)]
use std::{
fmt::Display,
fs::File,
io::{self, BufRead, BufReader},
panic::Location,
path::Path,
};
type Gizmo = Result<io::Result<Vec<String>>>;
fn slurp(path: impl AsRef<Path> + Display) -> Gizmo {
let file = File::open(&path)
.with_context(|| format!("Failed to open `{path}` at {}",
Location::caller()))?;
let buffer = BufReader::new(file);
let lines = buffer.lines().collect();
Ok(lines)
}
fn main() -> Result<()> {
let path = "test.dat";
if let Ok(lines) = slurp(&path)? {
for line in lines {
println!("{} ", line);
}
}
Ok(())
}
#2 with push()
type Gizmo = Result<Vec<String>>;
fn slurp(path: impl AsRef<Path> + Display) -> Gizmo {
let file = File::open(&path)
.with_context(|| format!("Failed to open `{path}` at {}",
Location::caller()))?;
let buffer = BufReader::new(file);
let mut lines = Vec::new();
for line in buffer.lines(){
lines.push(line?);
}
Ok(lines)
}
fn main() -> Result<()> {
let path = "test.dat";
if let Ok(lines) = slurp(&path) {
for line in lines {
println!("{} ", line);
}
}
Ok(())
}
How can i avoid to return a result of a result (like in version #2) using collect()
(and therefore slurp(&path)?
in main
) in version #1?