Rust Cargo 介绍

Cargo

Rust 的包管理工具,从项目的建立、构建到测试、运行直至部署,为 Rust 项目的管理提供尽可能完整的手段。

Cargo 创建新项目

直接输入

$ cargo new hello_world

       Created binary (application) `hello_world` package

创建的项目结构,进入到 hello_world 文件夹

.
├── Cargo.toml
├── .git
│   ├── ......
├── .gitignore
└── src
    └── main.rs

运行项目

两种方式

  • cargo run
  • 编译后运行
  1. 直接在项目根目录下运行
# cargo run
   Compiling hello_world v0.1.0 (/opt/rust/hello_world)
    Finished dev [unoptimized + debuginfo] target(s) in 1.08s
     Running `target/debug/hello_world`
Hello, world!
  1. 编译后运行
    编译
# cargo build
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s

在 ./target/debug/ 下生成二进制文件

运行

# ./target/debug/hello_world 
Hello, world!

debug && release && check

debug
默认情况下,cargo 默认是 debug 模式,就像上节直接生成在 target/debug 路径下一样
该模式下,rust 编译器不会做任何优化,编译速度会非常快,但运行速度慢

release
相对 debug,如果想要高性能程序,需要加上 --release

cargo run --release

cargo build --release

release 模式下生成的二进制文件在 target/release 下

check
cargo check 是用来验证代码正确性的工具,快速检查代码是否可以编译过,速度非常快。

# cargo check
    Checking hello_world v0.1.0 (/opt/rust/hello_world)
    Finished dev [unoptimized + debuginfo] target(s) in 0.18s

Cargo.toml 和 Cargo.lock

Cargo.toml 和 Cargo.lock 是 cargo 的核心文件,它的所有活动均基于此二者。

  • Cargo.toml 是 cargo 特有的项目数据描述文件。它存储了项目的所有元配置信息,如果 Rust 开发者希望 Rust 项目能够按照期望的方式进行构建、测试和运行,那么,必须按照合理的方式构建 Cargo.toml。

  • Cargo.lock 文件是 cargo 工具根据同一项目的 toml 文件生成的项目依赖详细清单,因此我们一般不用修改它。

什么情况下该把 Cargo.lock 上传到 git 仓库里?很简单,当你的项目是一个可运行的程序时,就上传 Cargo.lock,如果是一个依赖库项目,那么请把它添加到 .gitignore 中

Cargo.toml

package 配置段落

[package]
name = "hello_world"
version = "0.1.0"
edition = "2021"

name:项目名称
version:当前版本
edition:使用的 Rust 大版本

定义项目依赖

使用 cargo 工具的最大优势就在于,能够对该项目的各种依赖项进行方便、统一和灵活的管理。

在 Cargo.toml 中,主要通过各种依赖段落来描述该项目的各种依赖项:

  • 基于 Rust 官方仓库 crates.io,通过版本说明来描述
  • 基于项目源代码的 git 仓库地址,通过 URL 来描述
  • 基于本地项目的绝对路径或者相对路径,通过类 Unix 模式的路径来描述
[dependencies]
rand = "0.3"
hammer = { version = "0.5.0"}
color = { git = "https://github.com/bjz/color-rs" }
geometry = { path = "crates/geometry" }

标准的 package 目录结构

  • Cargo.toml 和 Cargo.lock 保存在 package 根目录下
  • 源代码放在 src 目录下
  • 默认的 lib 包根是 src/lib.rs
  • 默认的二进制包根是 src/main.rs
  • 其它二进制包根放在 src/bin/ 目录下
  • 基准测试 benchmark 放在 benches 目录下
  • 示例代码放在 examples 目录下
  • 集成测试代码放在 tests 目录下

此外,bin、tests、examples 等目录路径都可以通过配置文件进行配置,它们被统一称之为 Cargo Target。

参考:https://course.rs/about-book.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值