My first rust program, feel it

It's the weekend, and I have to learn something that makes me happy.

I heard that the rust language is very young, its performance exceeds C++, and it can also support embedded programming. As a code engineer who will become famous in the future, how can I miss it? So I started learning the language last week.

Following the book, I completed the first small program, guess_number, (what? It’s not “hello world”??) because I randomly generate a program, the template is helloworld, and I don’t need to write it at all. In terms of the speed of outputting hello world, rust only needs Two instructions, this is quite strong.

First go to the code and see:

use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn main() {
    println!("Guess the number!");
    
    let secret_number=rand::thread_rng().gen_range(1,101);
    
    //println!("The secret number is:{}",secret_number);
    loop{
	    println!("Please input your guess");
	    
	    let mut guess = String::new();
	    
	    io::stdin().read_line(&mut guess).expect("Failed to read line");
	    
	    //let guess:u32 = guess.trim().parse().expect("Please type a number!");
	    let guess:u32 = match guess.trim().parse() {
	    	Ok(num) => num,
	    	Err(_) => continue,
		};
	    
	    println!("You guessed:{}",guess);
	    
	    match guess.cmp(&secret_number)
	    {
	    	Ordering::Less => println!("Too small!"),
	    	Ordering::Greater => println!("Too big!"),
	    	Ordering::Equal => {
				println!("You win!");
				break;
			}
		}
	}
}

I used dev C++ to write this code. I heard that there is no special editor. I will try notepad later--what does it feel like to write this domestic software.

The use usage in the above code feels like a combination of C++ and python, omitting the inclusion of header files, and the crate used is very similar to the python package. fn main() has the feeling of C language in an instant, but I don't know where the return value of the function is. let defines a constant, and mut means variable. The return value of the function is processed by expect or match, and if it is not processed, it will warn. The same is match, some places write semicolons; some places write commas, and I don’t know why yet. The cycle uses loop, which is the familiar program structure of arduino. The statement block of {} is still in C language, and I don’t choose python’s indentation usage, which I think is right.

I feel so much at the moment, how to run the program, see the tutorial on the official website Getting Started - Rust Programming Language (rust-lang.org)

Good night, 2023-3-10 22:38 

Guess you like

Origin blog.csdn.net/weixin_41579872/article/details/129454977