Rust

2025年11月03日更新 13 人订阅
原价: ¥ 6 限时优惠
专栏简介

Rust编程语言之Cargo、Crates.io详解

Rust编程语言之Cargo、Crates.io详解内容通过releaseprofile来自定义构建在https://crates.io/上发布库通过workspaces组织大工程从https://crates.io/来安装库使用自定义命令扩展cargo一、通过re

Rust编程语言之Cargo、Crates.io详解

内容

一、通过 release profile 来自定义构建

release profile (发布配置)

  • release profile:
    • 是预定义的
    • 可自定义:可使用不同的配置,对代码编译拥有更多的控制
  • 每个 profile 的配置都独立于其它的 profile
  • cargo 主要的两个 profile:
    • dev profile:适用于开发,cargo build
    • release profile:适用于发布,cargo build --release

自定义 profile

  • 针对每个 profile,Cargo 都提供了默认的配置
  • 如果想自定义 xxxx profile 的配置:
    • 可以在 Cargo.toml 里添加 [profile.xxxx] 区域,在里面覆盖默认配置的子集
[package]
name = "closure"
version = "0.1.0"
edition = "2021"

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

[dependencies]

[profile.dev]
opt-level = 1

[profile.release]
opt-level = 3

执行

closure on  master [?] is 📦 0.1.0 via 🦀 1.67.1 took 2.9s 
➜ cargo build
   Compiling closure v0.1.0 (/Users/qiaopengjun/rust/closure)
    Finished dev [optimized + debuginfo] target(s) in 0.16s

closure on  master [?] is 📦 0.1.0 via 🦀 1.67.1 
➜ 

二、发布 crate 到 crates.io (1)

Crates.io

  • 可以通过发布包来共享你的代码
  • crate 的注册表在 <https://crates.io/>
    • 它会分发已注册的包的源代码
    • 主要托管开源的代码

文档注释

  • 文档注释:用于生成文档
    • 生成 HTML 文档
    • 显式公共 API 的文档注释:如何使用API
    • 使用 ///
    • 支持 Markdown
    • 放置在被说明条目之前

生成 HTML 文档的命令

  • cargo doc
    • 它会运行 rustdoc 工具(Rust 安装包自带)
    • 把生成的 HTML 文档放在 target/doc 目录下
  • cargo doc --open:
    • 构建当前crate的文档(也包含 crate 依赖项的文档)
    • 在浏览器打开文档
/// 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
}

运行

closure on  master [?] is 📦 0.1.0 via 🦀 1.67.1 
➜ cargo doc  
 Documenting closure v0.1.0 (/Users/qiaopengjun/rust/closure)
    Finished dev [optimized + debuginfo] target(s) in 0.39s

closure on  master [?] is 📦 0.1.0 via 🦀 1.67.1 
➜ cargo doc --open
    Finished dev [optimized + debuginfo] target(s) in 0.00s
     Opening /Users/qiaopengjun/rust/closure/target/doc/closure/index.html

closure on  master [?] is 📦 0.1.0 via 🦀 1.67.1 
➜ cargo doc --open
 Documenting closure v0.1.0 (/Users/qiaopengjun/rust/closure)
    Finished dev [optimized + debuginfo] target(s) in 0.41s
     Opening /Users/qiaopengjun/rust/closure/target/doc/closure/index.html

closure on  master [?] is 📦 0.1.0 via 🦀 1.67.1 

常用章节

  • # Examples
  • 其它常用的章节:
    • Panics:函数可能发生 panic 的场景
    • Errors:如果函数返回 Result,描述可能的错误种类,以及可导致错误的条件
    • Safety:如果函数处于 unsafe 调用,就应该解释函数 unsafe 的原因,以及调用者确保的使用前提。

文档注释作为测试

  • 示例代码块的附加值:
    • 运行 cargo test:将把文档注释中的示例代码作为测试来运行
/// Adds one to the number given.
/// 
/// # Examples
/// 
/// ```
/// let arg = 5;
/// let answer = closure::add_one(arg);
/// 
/// assert_eq!(6, answer);
/// ```
pub fn add_one(x: i32) -> i32 {
    x + 1
}

为包含注释的项添加文档注释

  • 符号://!
  • 这类注释通常用描述 crate 和模块:
    • crate root(按惯例 src/lib.rs)
    • 一个模块内,将 crate 或模块作为一个整体进行记录
//! # Closure Crate
//! 
//! `closure` is a collection of utilities to make performance
//! calculations more convenient.

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

三、pub use

使用 pub use 导出方便使用的公共 API

  • 问题:crate 的程序结构在开发时对于开发者很合理,但对于它的使用者不够方便
    • 开发者会把程序结构分为很多层,使用者想找到这种深层结构中的某个类型很费劲
  • 例如:
    • 麻烦:my_crate::some_module::another_module::UsefulType;
    • 方便:my_crate::UsefulType;
  • 解决办法:
    • 不需要重新组织内部代码结构
    • 使用pub use:可以重新导出,创建一个与内部私有结构不同的对外公共结构
//! # Art
//! 
//! A library for modeling artistic concepts.

pub mod kinds {
    /// The primary colors according to the RYB color model.
    pub enum PrimaryColor {
        Red,
        Yellow,
        Blue,
    }

    /// The secondary colors according to the RYB color model.
    pub enum SecondaryColor {
        Orange,
        Green,
        Purple,
    }
}

pub mod utils {
    use crate::kinds::*;

    /// Combines two primary colors in equal amounts to create
    /// a secondary color.
    pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor {
        SecondaryColor::Green
    }
}

src/main.rs 文件

use art::kinds::PrimaryColor;
use art::utils::mix;

fn main() {
    let red = PrimaryColor::Red;
    let yellow = PrimaryColor::Yellow;
    mix(red, yellow);
}

优化之后:

src/lib.rs 文件

//! # Art
//! 
//! A library for modeling artistic concepts.

pub use self::kinds::PrimaryColor;
pub use self::kinds::SecondaryColor;
pub use self::utils::mix;

pub mod kinds {
    /// The primary colors according to the RYB color model.
    pub enum PrimaryColor {
        Red,
        Yellow,
        Blue,
    }

    /// The secondary colors according to the RYB color model.
    pub enum SecondaryColor {
        Orange,
        Green,
        Purple,
    }
}

pub mod utils {
    use crate::kinds::*;

    /// Combines two primary colors in equal amounts to create
    /// a secondary color.
    pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor {
        SecondaryColor::Green
    }
}

src/main.rs 文件

// use art::kinds::PrimaryColor;
// use art::utils::mix;
use art::PrimaryColor;
use art::mix;

fn main() {
    let red = PrimaryColor::Red;
    let yellow = PrimaryColor::Yellow;
    mix(red, yellow);
}

四、发布 crate 到 crates.io(2)

创建并设置 Crates.io 账号

  • 发布 crate 前,需要在 crates.io 创建账号并获得 API token
  • 运行命令:cargo login [你的 API token]
    • 通知 cargo,你的 API token 存储在本地 ~/.cargo/credentials
  • API token 可以在<https://crates.io/>进行撤销

为新的crate 添加元数据

  • 在发布crate之前,需要在 Cargo.toml 的 [package] 区域为 crate 添加一些元数据:
    • crate 需要唯一的名称:name
    • description:一两句话即可,会出现在 crate 搜索的结果里
    • license:需提供许可证标识值(可到 <http://spdx.org/licenses/>查找
    • 可指定多个 license:用 OR
    • version
    • author
  • 发布:cargo publish 命令
rust_tutorials on  master [?] via 🦀 1.67.1 
➜ cargo login --registry crates-io               
please paste the token found on https://crates.io/me below
ciopLk54SDAxB200gA4jk85abcdefgabcabc # token
       Login token for `crates-io` saved

rust_tutorials on  master [?] via 🦀 1.67.1 took 1m 27.6s 
➜ 

rust_tutorials on  master [?] via 🦀 1.67.1 took 2.0s 
➜ cargo publish --registry crates-io --allow-dirty
    Updating crates.io index

发布到 Crates.io

  • Crate 一旦发布,就是永久性的:该版本无法覆盖,代码无法删除
    • 目的:依赖于该版本的项目可继续正常工作

发布已存在 crate 的新版本

使用 cargo yank 从 Crates.io 撤回版本

  • 不可以删除 crate 之前的版本
  • 但可...

剩余50%的内容订阅专栏后可查看

点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论