Rust basic notes: getting input from the console

Time:2021-12-3

An example

Rust can get user input from the console like other programming languages, but the processing method of rust is very different from other languages, which has a lot of things worth learning and thinking about.
Start with a small example:

    let mut buf = String::new();
    io::stdin().read_line(&mut buf);

analysis

Let’s take a look at what IO:: stdin() returns in the manual:

Stdin is a structure and implements a called read_ The method of line() looks like this:

Its job is to read a line of user input from the console, write it into buf and compile it. There is no error, but a warning is given:

warning: unused result which must be used, #[warn(unused_must_use)] on by default

It can be seen that our work has not been completed because read_ The line () method does not directly return the read length, but wraps the length value with rusult. Why?

Because from a security point of view, getting input from the console may succeed or fail, and read_ The return value result of line() contains two possibilities of success and failure. You must deal with it. Let’s take a look at the structure of the result first:(https://doc.rust-lang.org/stable/std/result/enum.Result.html

    enum Result<T, E> {
        Ok(T),
        Err(E)
    }

The correct result will be included in OK, and err will be returned in case of error. The result has implemented relevant judgment functions, such as is_ ok(),is_ Err (), here we emphasize the OK () and err () methods. See the manual:

It can be seen from the document that if the result is correct, it will be converted to option:: some. If it is wrong, it will be converted to option:: none. After the conversion of OK (), the right and wrong results in the previous processing will be converted into expected data and empty. In the above small example, if there is no error, The data will be stored in buf. What if it fails? Then you can only prompt an error. Let’s see how to handle the error in this last step.

In the previous description, the OK () method returns an option. In this example, we only need to deal with option:: none. That is, if this is none, nothing will be obtained in buf and an error will be prompted.

Let’s take a look at the enum of option (refer to the document:https://doc.rust-lang.org/stable/std/option/enum.Option.html)

    enum Option<T> {
       None,
       Some(T),
    }

It is similar to result, and we use an implemented method called: expect (), which is declared in the document as follows:

In other words, it will judge whether the option is some or none. If it is some, it will take out the T and return it. If it encounters none, it will make an error and print the string in the parameter as an error message.

At this time, let’s finish the procedure and summarize:

use std::io;
    fn main() {
        let mut buf = String::new();
        println! ("Please input your name:"); //  This line of output needs to contain a newline character, otherwise you can't see it until you finish typing
        io::stdin().read_line(&mut buf).ok().expect("Error!");
        println!("Hello {} !", buf);
    }

The output is as follows:

Why did you run down here? The reason is:
The reason is that our input just now contains a carriage return character, and rust is put into buf together with the line feed character, which is obviously not what we want, so we should deal with this carriage return character here, and then the above code:

    let name = buf.trim();
    println!("Hello {} !", name);

The trim method is very simple. Like the trim function in most other languages, it is to remove redundant characters on both sides of the string. See
https://doc.rust-lang.org/stable/std/string/struct.String.html#method.trim

Recompile and the result will be normal:

Tidy up:

    use std::io;
    fn main() {
        let mut buf = String::new();
        println!("Please input your name:");
        io::stdin().read_line(&mut buf).ok().expect("Error!");
        let name = buf.trim();
        println!("Hello {} !", name);
    }

Summary

It can be seen from the above code that we have never used a processing method similar to if err everywhere in golang. Is it very elegant that all operations are completed in one line? Among them, result and option play a very important role. There are many such usage methods in rust. We need to understand the role of these two enums.