Use Result<T, E> to return either a success value of type T or an error of type E from functions that might fail. Return Ok(value) on success and Err(error) on failure, then handle the result using match or the ? operator to propagate errors.
use std::fs::File;
use std::io::Error;
fn read_file(path: &str) -> Result<String, Error> {
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn main() {
match read_file("hello.txt") {
Ok(contents) => println!("File contents: {}", contents),
Err(e) => eprintln!("Error reading file: {}", e),
}
}