01-Rust的基础知识

第一章 Rust 的基础知识

1. 安装、更新

  • 官网:https://www.rust-lang.org

  • 安装步骤(Windows):

    • 在准备安装目录下创建.cargorustup目录

      安装目录

    • 在系统变量中创建两个变量:CARGO_HOMERUSTUP_HOME,分别对应上面创建的连个目录

      CARGO_HOME

      RUSTUP_HOME

    • 下载对应的 rustup

      安装页面

    • 使用管理员身份运行rustup-init.exe进行安装

    • 安装过程中会自动弹出 Visual Studio 的安装程序,按照要求安装即可

      安装VS

    • 安装完 VS,下面输入 1 进行安装即可

      安装

    • 安装完成,按回车键(Enter)退出

      安装完成

  • 更新 Rust

    • 更新 Rust

      rustup update
      
    • 卸载 Rust

      rustup self uninstall
      
    • 添加组件

      rustup component add rustfmt
      
    • 查看版本

      rustup --version
      
    • 安装稳定版(Stable)或夜版(Nightly)

      rustup install stable/nightly
      
    • 切换稳定版(Stable)或夜版(Nightly)

      rustup default stable/nightly
      

2. 编译器与包管理工具以及开发环境搭建

  • Rust 编程语言的编译器 rustc

    • 查看版本

      rustc --version
      
    • 编译生成二进制文件

      rustc -o output_filename filename.rs
      
    • 编译生成库文件

      rustc --crate-type lib filename.rs
      
  • 隐式使用 rustc 进行编译

    • 创建

      cargo new project_name
      
      cargo new --lib project_name  # 创建一个新的Rust库项目
      
    • 构建项目

      cargo build
      
      cargo build --release  # 为生产环境生成优化后的可执行文件
      
    • 检测

      cargo check
      
    • 运行/测试

      cargo run  # 运行
      cargo test  # 测试
      

3. 获取 Rust 的库、国内源以及 Windows 与 Linux 和 Mac 的不同

  • 第三方库的官方网站:https://crates.io

  • 添加库

    cargo add dependency_name
    
    • 安装指定版本

      cargo add dependency_name@1.2.3
      
    • 添加开发依赖

      cargo add --dev dev_dependency_name
      
    • 添加构建依赖

      cargo add --build build_dependency_name
      
  • 删除库

    cargo rm dependency_name
    
  • 国内源推荐网站:https://rsproxy.cn/

posted @ 2025-07-09 09:47  DongCha  阅读(17)  评论(0)    收藏  举报