cargo
常用 Cargo 命令
新建项目:
cargo new 项目名
创建一个新的二进制项目,生成一个包含
Cargo.toml
文件和一个简单的main.rs
文件的目录。构建项目:
cargo build
构建项目的可执行文件。生成的文件会放在
target/debug
目录下。运行项目:
cargo run
构建并运行当前项目。
测试项目:
cargo test
运行项目中的所有测试。
发布项目:
cargo build --release
构建发布版本的可执行文件,生成的文件会放在
target/release
目录下。添加依赖:
cargo add 依赖名
添加新的依赖项到
Cargo.toml
文件中。检查项目:
cargo check
检查项目代码是否有错误,但不生成可执行文件,速度比
cargo build
更快。在项目中使用特定版本的 Rust: 在项目根目录创建或修改
rust-toolchain
文件,内容如下:[toolchain] channel = "版本号"
例如,指定项目使用 1.60.0 版本:
[toolchain] channel = "1.60.0"
rustup
rustup
是 Rust 的工具链安装和管理工具,提供了多种命令来管理 Rust 的版本和组件。以下是一些常用的 rustup
命令和用法:
常用 rustup
命令
安装 Rust:
rustup install stable # 安装 stable 版本 rustup install nightly # 安装 nightly 版本 rustup install beta # 安装 beta 版本
设置默认版本:
rustup default stable # 设置默认版本为 stable rustup default nightly # 设置默认版本为 nightly
查看已安装的工具链:
rustup toolchain list
更新 Rust:
rustup update stable # 更新 stable 版本 rustup update nightly # 更新 nightly 版本 rustup update # 更新所有已安装的版本
卸载 Rust 工具链:
rustup toolchain uninstall nightly
查看可用组件:
rustup component list
添加组件:
rustup component add 组件名
卸载组件:
rustup component remove 组件名
使用 rustup
安装 Clippy 和 Rustfmt
Clippy 和 Rustfmt 是 Rust 的两个非常有用的工具,分别用于代码静态分析和代码格式化。你可以通过 rustup
轻松安装它们:
安装 Clippy:
rustup component add clippy
安装 Rustfmt:
rustup component add rustfmt
在特定工具链上安装 Clippy 和 Rustfmt: 如果你想在特定的工具链(例如 nightly)上安装这些组件,可以指定工具链:
rustup component add clippy --toolchain nightly rustup component add rustfmt --toolchain nightly
rustup
提供了安装和管理 Rust 组件的功能,以下是一些 Rust 开发中常用的组件及其安装方法:
常用组件
Clippy: Rust 代码的静态分析工具,用于发现常见的编程错误和改进代码质量。
rustup component add clippy
Rustfmt: Rust 代码格式化工具,用于确保代码符合标准的代码风格。
rustup component add rustfmt
Rust分析器(Rust Analyzer): 用于提供 IDE 支持的语言服务器协议(LSP)工具。
rustup component add rust-analyzer
LLVM 工具: Rust 使用 LLVM 作为其后端编译器工具链,提供了许多有用的开发工具。
rustup component add llvm-tools-preview
MIRI: Rust 中的解释器,用于运行和检测 Rust 程序中的未定义行为。
rustup component add miri
安装组件命令示例
下面是一些常用组件的安装命令示例:
# 安装 Clippy
rustup component add clippy
# 安装 Rustfmt
rustup component add rustfmt
# 安装 Rust 分析器
rustup component add rust-analyzer
# 安装 LLVM 工具
rustup component add llvm-tools-preview
# 安装 MIRI
rustup component add miri
在特定工具链上安装组件
如果你需要在特定工具链(例如 nightly 或 beta)上安装这些组件,可以通过 --toolchain
选项指定工具链。例如:
# 在 nightly 工具链上安装 Clippy
rustup component add clippy --toolchain nightly
# 在 nightly 工具链上安装 Rustfmt
rustup component add rustfmt --toolchain nightly
# 在 nightly 工具链上安装 Rust 分析器
rustup component add rust-analyzer --toolchain nightly
# 在 nightly 工具链上安装 LLVM 工具
rustup component add llvm-tools-preview --toolchain nightly
# 在 nightly 工具链上安装 MIRI
rustup component add miri --toolchain nightly
通过这些命令,你可以灵活地安装和管理 Rust 开发所需的各种组件。