Rust 浅学猜数字游戏实现

50 阅读1分钟

简介

了解了rust的安装和hello world之后,通过学习一个猜数字游戏的编程案例,浅学下rust语言。

代码

  • main.rs
use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn main() {
    println!("Guess the name!");
    println!("Please input your guess.");

    let secret_number = rand::rng().random_range(1..101);
    println!("The secret number is: {}", secret_number);

    loop {
        let mut guess = String::new();
        io::stdin()
        .read_line(&mut guess)
        .expect("Failed to read line");
    
        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;
            }
        }
    } 
}

总结

  • cargo 命令用于创建管理项目
    • build, b Compile the current package
    • check, c Analyze the current package and report errors, but don't build object files
    • clean Remove the target directory
    • doc, d Build this package's and its dependencies' documentation
    • new Create a new cargo package
    • init Create a new cargo package in an existing directory
    • add Add dependencies to a manifest file
    • remove Remove dependencies from a manifest file
    • run, r Run a binary or example of the local package
    • test, t Run the tests
    • bench Run the benchmarks
    • update Update dependencies listed in Cargo.lock
    • search Search registry for crates
    • publish Package and upload this package to the registry
    • install Install a Rust binary
    • uninstall Uninstall a Rust binary
  • Cargo.toml 定义了项目的元数据、依赖关系、构建选项等关键信息
  • use 用于将路径引入当前作用域,从而简化对模块项的调用
  • :: 是路径分隔符,用于访问模块、枚举变体、关联函数、静态变量等
  • : 主要用于类型标注
  • ! 意味着调用的是宏而不是普通的函数
  • let 用于引入新的变量到当前作用域中,默认情况下变量是不可变的
  • mul 声明为可变变量
  • .. 区间表达式start..end。它包括起始端,但排除终止端
  • loop 循环
  • & 引用
  • match 条件语句,可以方便地匹配不同枚举值来执行不同的代码