3 在本地运行 Cargo
03-在本地运行 Cargo — Comprehensive Rust
2 分钟阅读
译文 · 基于 Comprehensive Rust
原文链接: https://google.github.io/comprehensive-rust/cargo/running-locally.html
3 在本地运行 Cargo
若想在自己的系统上试验代码,需要先安装 Rust。请按
《The Rust Book》中的说明 操作。完成后应能使用 rustc 与
cargo。撰写本文时,最新稳定版 Rust 的版本号如下:
| |
也可以使用之后的任意版本,因为 Rust 保持向后兼容。
准备好后,按下列步骤把本培训中的示例构建为 Rust 二进制:
在要复制的示例上点击「Copy to clipboard」按钮。
用
cargo new exercise创建新的exercise/目录存放代码:1 2$ cargo new exercise Created binary (application) `exercise` package进入
exercise/,用cargo run构建并运行二进制:1 2 3 4 5 6$ 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如下所示:1 2 3 4 5 6// Copyright 2022 Google LLC // SPDX-License-Identifier: Apache-2.0 # fn main() { println!("Edit me!"); }用
cargo run构建并运行更新后的二进制:1 2 3 4 5$ 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编译但不运行。普通 debug 构建的输出在target/debug/。用cargo build --release可在target/release/生成优化后的 release 构建。可通过编辑
Cargo.toml为项目添加依赖。运行cargo命令时,它会自动下载并编译缺失的依赖。
尽量鼓励学员安装 Cargo 并使用本地编辑器。这样他们会有正常的开发环境,使用更方便。