Getting information in

Up to this point, we have concentrated on getting information out from a Rust program rather than entering information.

Input is done via the std::io module, getting a reader using the io::stdin() function, and then calling read_line on that reader. We put the inputted data into a dynamically growing String, which needs to be mutable.

A simple example for inputting would look like this:

// 03/readline/src/main.rs
use std::io; fn main() { let reader: io::Stdin = io::stdin(); let mut input_text: String = String::new(); reader.read_line(&mut input_text).expect("Reading failed"); println!("Read {}", input_text); }

We can see Rust's error handling in action in the previous code. The read_line method returns a result type, which means that the operation could have failed. The result type encapsulates two generic types inside itself, which in the case of read_line are usize (for reporting how many bytes were read in) and io::Error (for reporting any errors during input). The actual read String is placed in the first argument of the function, in this case input_text.

On that result type, our example calls the expect method. It expects that everything went fine, and returns the first value (the usize in this case). If there were errors, the expect method prints reading failed to the standard output and exits the program.

This is not the only way to handle result types, but it's a common one in cases where we expect things to usually work out fine.

Another way to handle the error is to explicitly call the is_err method on the result. It returns a boolean, like this:

    let result: Result<usize, io::Error> = reader.read_line(&mut input_text); 
    if result.is_err() { 
        println!("failed to read from stdin"); 
        return; 
    } 

If we wish to further parse the entry into another type, we can use the parse method.

For instance, say we'd like to get an i32 from the input. The read_line method includes a carriage return in the input data, so we need to get rid of that using the trim method before parsing:

    let trimmed = input_text.trim(); 
    let option: Option<i32> = trimmed.parse::<i32>().ok(); 

For the sake of this example, this final line converts the result type into an Option using the ok method. Option is a simplified version of result. This is a useful library and it can have one of two results: Some or None.

Here, if the entry result is None, the value is not an integer, whereas Some would be an integer:

match option { 
        Some(i) => println!("your integer input: {}", i), 
        None => println!("this was not an integer: {}", trimmed) 
    }; 
 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset