WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Basic · question 20 of 100

How do you handle errors in Rust? Provide an example using the Result type.?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

Rust’s error handling system is based on the Result type, which is an enum with two variants:

When a function can fail, it returns a ‘Result<T, E>‘ type where ‘T‘ is the successful result type, and ‘E‘ is the error type.

Here’s an example of how to handle errors in Rust using the Result type:

    use std::fs::File;
    use std::io::{self, prelude::*, BufReader};
    
    fn read_file_lines(file_path: &str) -> Result<Vec<String>, io::Error> {
        let file = File::open(file_path)?;
        let reader = BufReader::new(file);
        let lines = reader.lines().map(|line| line.unwrap()).collect();
        
        Ok(lines)
    }
    
    fn main() -> Result<(), io::Error> {
        let file_path = "my_file.txt";
        let lines = read_file_lines(file_path)?;
        
        for line in lines {
            println!("{}", line);
        }
        
        Ok(())
    }

In this example, ‘read_file_lines‘ is a function that reads all lines from a file and returns them as a vector of strings. The function returns a ‘Result<Vec<String>, io::Error>‘ type, where ‘Vec<String>‘ is the successful result type, and ‘io::Error‘ is the error type.

Inside the function, we open the file using ‘File::open‘, which returns a ‘Result<File, io::Error>‘ type. We use the ‘?‘ operator to propagate any errors from ‘File::open‘ up to the caller. If the file is opened successfully, we create a ‘BufReader‘ from the file and use its ‘lines‘ method to get an iterator over all lines in the file.

We then use ‘map‘ to convert the ‘Result<io::Result<String>, io::Error>‘ iterator into an iterator over ‘String‘s. We use ‘unwrap‘ to panick if there is an error on any of the lines. Finally, we collect the iterator into a vector of strings and return it as a successful result.

In the ‘main‘ function, we call ‘read_file_lines‘ with the file path and use the ‘?‘ operator again to propagate any errors up to the caller. If the function returns successfully, we print each line to the console.

If an error occurs during the execution of ‘read_file_lines‘, it will be returned as an ‘io::Error‘ type and propagated up to the caller of ‘main‘.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics