使用 Cargo 在本地运行代码
如果你想在自己的系统上对代码进行实验, 则需要先安装 Rust。为此,请按照 Rust 图书中的 说明操作。这应会为你提供一个有效的 rustc 和 cargo。在撰写 本文时,最新的 Rust 稳定版具有以下版本号:
% rustc --version
rustc 1.69.0 (84c898d65 2023-04-16)
% cargo --version
cargo 1.69.0 (6e9a83356 2023-04-12)
您也可以使用任何更高版本,因为 Rust 保持向后兼容性。
了解这些信息后,请按照以下步骤从本培训中的 一个示例中构建 Rust 二进制文件:
-
在你要复制的示例上点击“复制到剪贴板”按钮。
-
使用
cargo new exercise为你的代码新建一个exercise/目录:$ cargo new exercise Created binary (application) `exercise` package -
导航至
exercise/并使用cargo run构建并运行你的二进制文件:$ cd exercise $ cargo run Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise) Finished dev [unoptimized + debuginfo] target(s) in 0.75s Running `target/debug/exercise` Hello, world! -
将
src/main.rs中的样板代码替换为你自己的代码。例如, 使用上一页中的示例,将src/main.rs改为:fn main() { println!("Edit me!"); } -
使用
cargo run构建并运行你更新后的二进制文件:$ cargo run Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise) Finished dev [unoptimized + debuginfo] target(s) in 0.24s Running `target/debug/exercise` Edit me! -
使用
cargo check快速检查项目是否存在错误;使用cargo build只进行编译,而不运行。你可以在target/debug/中找到常规调试 build 的输出。使用cargo build --release在target/release/中生成经过优化的 发布 build。 -
你可以通过修改
Cargo.toml为项目添加依赖项。当你 运行cargo命令时,系统会自动为你下载和编译缺失 的依赖项。
尽量鼓励全班学员安装 Cargo 并使用 本地编辑器。这能为他们营造常规 开发环境,让工作变得更加轻松。