Skip to content

Cargo

http://llever.com/cargo-book-zh/

https://doc.rust-lang.org/cargo/index.html

命令

cargo run --release在生产环境使用,直接cargo run使用的是 debug 模式,性能会和实际比较会差很多倍

限制编译时使用 CPU 核数:

~/.cargo/config中添加

1
2
[build]
jobs = 8

表示限制到 8 个核

Cargo.toml 中使用 gitlab/github 项目

http://llever.com/cargo-book-zh/reference/specifying-dependencies.zh.html

~/.cargo/config中添加

1
2
[net]
git-fetch-with-cli = true

如果未指定任何其他信息,Cargo 假定我们打算使用最新的提交master分支,来构建我们的包。
可以将 git 字段和 rev,tag, 还有 branch,这些用于指定其他内容的字段组合起来。gitlab 和 github 都一样

Cargo.toml:

1
async-tls = { git = "ssh://git@code.xxx.com/zhaoyz/async-tls.git", branch = "server_add_get_cert_func" }

也可以使用 tag

1
async-tls = { git = "https://example/xxx/async-tls.git", tag = "0.8.0" }

Cargo.lock

cargo new xxx 时 .gitignore 不会添加 Cargo.lock
cargo new --lib xxx 时 .gitginore 会添加 Cargo.lock

cargo-sweep

对于nightly通道的用户来说,通常在使用过程中会伴随着频繁的升级你的rust版本,而对于日常维护的项目,如果你升级了rust版本之后,target编译文件夹里面会生成多个版本的编译文件。这个时候就是使用cargo sweep的时候了,它会帮你清理掉除了当前版本以外的target目录下多余的文件。

用例: cargo sweep -i -r -v ~/src

  • -i 是开启保留~/src目录下target文件夹内当前电脑上已安装rust版本的编译文件。
  • -r 是开启递归(recursively)搜索
  • -v 是开启详细(啰嗦模式,开启之后会告诉你它干了啥。)

如果你的电脑上没有cargo sweep,可以用以下命令安装: cargo install cargo-sweep

cargo-udeps

找出项目中没有用到的依赖

https://github.com/est31/cargo-udeps

安装: cargo install cargo-udeps --locked

使用: cargo udeps

获取 gitlab 上的项目失败

例如在 Cargo.toml 中进行如下配置:

1
test_repo = { git = "ssh://git@code.xxx.com:2333/test/test_repo.git", tag = "0.0.3" }

报错:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
error: failed to get `test_repo` as a dependency of package `this_pack v0.0.3 (/home/zhaoyangzhen/mo-core)`

Caused by:
  failed to load source for dependency `test_repo`

Caused by:
  Unable to update ssh://git@code.q-phantom.com:2333/core/test_repo.git?tag=0.0.3

Caused by:
  process didn't exit successfully: `git fetch --tags --force --update-head-ok 'file:///home/zhaoyangzhen/.cargo/git/db/test_repo-xxxxxx' 'refs/heads/*:refs/remotes/origin/*' 'HEAD:refs/remotes/origin/HEAD'` (exit status: 128)
  --- stderr
  fatal: couldn't find remote ref HEAD
  fatal: the remote end hung up unexpectedly

解决方法:

删除 ~/.cargo/git/checkouts~/.cargo/git/db 这两个目录下的所有文件夹

gitlab

如果修改 gitlab 上项目相同标签为不同内容,需要删除 Cargo.lock 重新编译