Rust编程语言-14-Cargo和Crate进阶

Cargo Release Profile

cargo build 默认使用的dev 的profile
cargo build --release 使用的release 的profile

Cargo.toml 配置文件

[profile.dev]
opt-level = 0

[profile.release]
opt-level = 3

opt-level 取值从0-3, 0级别代表更快的编译速度,不太关注执行的速度,3代表用较慢的编译来获取快速的执行速度,适用于生产环境

发布Crate到Crate.io

///: 三个斜杠的注释来注释代码,提供更好的可读性,支持markdown语法

/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let arg = 5;
/// let answer = my_crate::add_one(arg);
///
/// assert_eq!(6, answer);
/// ```
pub fn add_one(x: i32) -> i32 {
    x + 1
}

执行cargo doc,生成html的文档在target/doc 目录下
cargo doc --open 会生成并打开html文档

//! # My Crate
//!
//! `my_crate` is a collection of utilities to make performing certain
//! calculations more convenient.

上面的注释使用了//! 形式的注释,一般放在lib.rs的最开始的部分,代表的是整个crate的注释,与///类型注释的使用场景有所区别

要发布一个crate

  • 先要在crate.io上申请一个账号
  • 然后执行, $ cargo login 登录
  • 修改cargo.toml ,内容形如
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2018"
description = "A fun game where you guess what number the computer has chosen."
license = "MIT OR Apache-2.0"

[dependencies]

  • 执行 cargo publish

标记某个版本的crate为不可用

如果某个版本的crate有问题,防止别人继续从crate.io上添加为依赖并拉取,命令形如
$ cargo yank --vers 1.0.1

Cargo workspace

比较大的项目,分拆成多个包,类似于java中父级maven下面有多个module

├── Cargo.lock
├── Cargo.toml
├── add-one
│   ├── Cargo.toml
│   └── src
│       └── lib.rs
├── adder
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── target

父级的cargo.toml 内容如下:

[workspace]

members = [
    "adder",
    "add-one",
]

你可能感兴趣的:(Rust编程语言-14-Cargo和Crate进阶)