Cargo:包管理工具

发布时间: 更新时间: 总字数:709 阅读时间:2m 作者: 分享 复制网址

CargoRust的构建系统和包管理工具,可以用来下载依赖库和构建代码,和 Golang Modules 的作用类似。

介绍

Cargo 在安装 Rust 时默认安装,使用如下命令查看版本:

$ cargo --version
cargo 1.62.0 (a748cf5a3 2022-06-08)

使用

创建项目

$ cargo new hello_cargo
     Created binary (application) `hello_cargo` package

$ tree hello_cargo
hello_cargo
├── Cargo.toml
└── src
    └── main.rs

1 directory, 2 files
  • Cargo.toml 配置文件
$ cat hello_cargo/Cargo.toml
[package]             # 包的配置信息
name = "hello_cargo"  # 项目名称
version = "0.1.0"     # 项目版本
edition = "2021"      # Rust 版本

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]        # 依赖
  • hello world 示例
$ cat hello_cargo/src/main.rs
fn main() {
    println!("Hello, world!");
}

说明:

  • Cargo.toml 使用 TOML(Tom’s Obvious Minimal Language) 格式的配置文件
  • src 目录存放 Rust 源代码

代码检查

运行较快,常用来检查代码

$ cd hello_cargo
$ cargo check
    Checking hello_cargo v0.1.0 (/Users/xiexianbin/workspace/code/github.com/xiexianbin/rust-study/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.66s

构建项目

  • 开发调试构建
$ cargo build
   Compiling hello_cargo v0.1.0 (/Users/xiexianbin/workspace/code/github.com/xiexianbin/rust-study/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 2.62s
$ tree -L 2
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
    ├── CACHEDIR.TAG
    └── debug

3 directories, 4 files

说明:

  • 自动生成 Cargo.lock 记录项目依赖的信息,自动生成。类似于 Golang 中的 go.sum 或 npm 的 yarn.lock/package.lock?
  • target 目录编译相关内容,target/debug/hello_cargo 为编译好的可执行文件
  • 发布构建,此过程编译时会进行优化,代码运行的更快,但编译时间更长,可执行文件默认发布在 target/release 目录
$ cargo build --release
   Compiling hello_cargo v0.1.0 (/Users/xiexianbin/workspace/code/github.com/xiexianbin/rust-study/hello_cargo)
    Finished release [optimized] target(s) in 0.90s
$ target/release/hello_cargo
Hello, world!

$ tree -L 2
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
    ├── CACHEDIR.TAG
    ├── debug
    └── release

4 directories, 4 files

运行项目

编译代码并运行,若之前编译过并且没有修改代码,自动识别使用之前的编译文件运行

$ cargo run
   Compiling hello_cargo v0.1.0 (/Users/xiexianbin/workspace/code/github.com/xiexianbin/rust-study/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.04s
     Running `target/debug/hello_cargo`
Hello, world!

说明:

  • Compiling 就是编译过程,若不修改代码,再次运行 cargo run 时不会执行该步骤

扩展 cargo 命令

cargo 被设计为可以使用子命令来扩展,如:

  • $PATH 目录下的二进制 cargo-something,可以使用 cargo something 调用
  • 优点:使用 cargo install 可以从 https://cargos.io 安装扩展,使其像内置工具一样来允许
  • 自定义命令列表:cargo --list

其他

  • 更新依赖:cargo update
  • 格式化:cargo fmt --all -- --check
  • cargo clippy -- -D warnings
  • cargo build --release --all-features
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数