This is the third day of my participation in Gwen Challenge.

Rust is a language that empowers everyone to build reliable and efficient software.

All the following examples and codes are based on the Mac environment, the editor is vscode, if you encounter any problems, welcome to join the exchange group, exchange together.

Rust numbers vs. NodeJS numbers

I remember learning NodeJS from this guessing game. I believe that you can write NodeJS guess the number game easily, I will not repeat. Let’s see how Rust implements it.

The input and output are the same

Output we have mastered, that how can receive input from the terminal, this is waiting for an IO library, that directly into the IO library. Use the use keyword to implement the import. :: is equivalent to module level path splitting, of course can also be generic specification and correlation functions, in this case path splitting. (Don’t ask anything, ask is -> rules). PS: Details will follow.

use std::io Const {IO} = require(' STD ') const {IO} = require(' STD '
// Use STD :: IO ::stdin or use STD are both acceptable syntax to be covered later, just to reassure you
fn main () {
    println!("Welcome to the number guessing game.");
    io::stdin().read_line(&mut str); 
}
Copy the code

The stdin function returns an instance of STD :: IO :: stdin, calls the read_line method on the instance, and receives it with the variable STR. What the hell is mut? And then we look down.

Create a mutable and immutable variable

Whereas Rust declares a variable to use the let keyword, in JavaScript variables created by the let keyword are mutable, Rust does the opposite. To create an immutable variable, you must use the MUT keyword. So let’s declare a variable STR.

use std::io;
fn main() {
    println!("Welcome to the number guessing game.");
    let mut str;
    stdin().read_line(&mut str);
}
Copy the code

Cargo build(equivalent to rustC main.rs) error when executing cargo build on terminal Because Rust is a strongly typed language, declared variables must be initialized. Since the terminal input is a string, we initialize a string.

use std::io;
fn main() {
    println!("Welcome to the number guessing game.");
    // New is a function associated with String that creates a new empty String and assigns the empty String to the variable STR
    let mut str = String::new(); // Similar to new String() in JavaScript
    stdin().read_line(&mut str);
}
Copy the code

Since STR is already a mutable variable, why use & and mut? There is a concept of ownership (which is the core of this later). Let’s look at the implementation of read_line:

pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
        self.lock().read_line(buf)
}
Copy the code

String::new() : String::new() : String::new() : String::new() : String::new() : String::new() : String::new() : String::new() : String::new() That is, the STR lends ownership of the resource to buF.

In JavaScript, the call to a function passes an object, and the function can modify the original object.

Handle exceptions

At this point we can add a line of output code and execute cargo Build

fn main () {
    // ...
    println!("You guessed the number: {}".str);
}
Copy the code

We run cargo run(equivalent to./main) and realize that we already have the desired result. We type the number on the terminal and press Enter. But this warning here makes code cleanliness fetish us very uncomfortable, how to eliminate it? Read_line returns a Result object. The members of Result are Ok and Err. The Ok member indicates that the operation succeeded. An Err member means that the operation failed and contains the cause and effect of the failure. These Result types are used to encode error handling information. A value of the Result type, like any other type, has a method defined on it. Instances of IO ::Result have expect methods. So let’s just add an Expect method. So the complete code is:

use std::io;
fn main() {
    println!("Welcome to the number guessing game.");
    let mut str = String::new();
    io::stdin().read_line(&mut str).expect("Failed to receive number, please re-enter");
    println!("You guessed the number: {}".str);
}
Copy the code

Pay attention to

A rust expression must have a semicolon

The rust String type must be double quotes

At the end

The next section: Chapter 3 Guessing Numbers (2)

Previous section: Rust from Entry to Escape – Part 2 Hello Word