Ask Your Question
2

What is the idiomatic approach to obtain accurate outcome messages from std::io?

asked 2023-05-19 14:41:55 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-19 14:47:01 +0000

lakamha gravatar image

The idiomatic approach to obtain accurate outcome messages from std::io is to use Result, which is a type that represents either success or failure, including an associated value or error message. For example, instead of directly reading from a file and printing error messages if the operation fails, you can wrap the operation in a Result and handle the different cases separately:

use std::fs::File;
use std::io::{Error, Read, Result};

fn read_file(filename: &str) -> Result<String> {
    let mut file = File::open(filename)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}

fn main() -> Result<()> {
    match read_file("input.txt") {
        Ok(contents) => println!("{}", contents),
        Err(error) => match error.kind() {
            ErrorKind::NotFound => println!("File not found"),
            _ => println!("Error reading file"),
        }
    }
    Ok(())
}

In this example, read_file returns a Result<string>, which indicates whether the operation was successful (Ok) and returns the file contents, or failed (Err) and returns an Error object. The error handling is done in main, where the different cases are matched and appropriate messages are printed.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-19 14:41:55 +0000

Seen: 9 times

Last updated: May 19 '23