Handling Failures

main.rs
use std::io;

fn main() {
    println!("Guess the number!");

    println!("Please input your guess.");

    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("Failed to read line");

    println!("You guessed: {}", guess);
}

read_line not only takes in a string, but it returns a value of type io::Result. A Result has a fixed set of values (aka it's an enumeration or enum). Those values are Ok and Err. As you might imagine, Ok has the value if the action is successful and Err contains the error. This bit:

.expect("Failed to read line");

allows you to handle the Err case. In this instance, you are unlikely to get an error. However, if you do not include that line, you will get a warning letting you know that you have an "unused result":

Last updated