This is the sixth 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.
The previous article has completed the operation of input and output from the terminal, since it is a guessing number of the game, the terminal input is always a string, how to get the number
Rust VS NodeJS type conversion
When you input a number from a terminal, the terminal still gets a string. This is the result of the IO operation. Therefore, you need to convert the received string to a number.
NodeJS type conversion
There are many ways to convert JavaScript types, such as Number,parseInt, etc
Number('1') = >1
Number('1') = >1
parseInt('1') = >1
parseInt('1') = >1
Copy the code
Rust conversion
Let STR: u32 = str.trim().parse(). Expect (“Please type a number!” );
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");
let str: u32 = str.trim().parse()
.expect("Please type a number!");
println!("You guessed the number: {}".str);
}
Copy the code
1. Why trim()
The trim() method is identical to the JavaScript method, removing whitespace at the beginning and end of the string. So when the number is entered, you must type the Enter key for read_line to return, but when the user presses the Enter key, a newline character is added to the string. For example, if the user types 5 and presses Enter, STR looks like this: 5\n. \n stands for “line feed”, enter key. The trim method eliminates \n, leaving only 5.
2. Why parse()
After formatting a useless operator, we are left with a pure string that could have been matched by /^\d+$/g. Parse, Rust’s type conversion function, can only convert pure numbers and is not as smart as JavaScript. Parse ::
(). Expect (“Please type a number!”) ); More on this later.
3, Why expect(“Please type a number!”) );
Because Rust does not provide type-checking methods like JavaScript’s Typeof, all parse methods go back to type checking and throw an exception as Result if type checking fails. In fact, we can not do exception catching, which is more suitable for unit testing.
let a = str.trim().parse::<u32> ()/ / = > 4
assert_eq!(Ok(4), str)
Copy the code
At the end
The next section: Chapter 3 Guessing Numbers (3)
Chapter 3 Guessing Numbers (2)