Rust 编程视频教程(进阶)——007_2 文档注释

视频地址

头条地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

讲解内容

编写有用的文档注释
(1)在基础部分,我们讲解了代码注释,通过//来注释;

(2)Rust也有特定的用于文档的注释类型,通常称为文档注释,它们会生成HTML文档。它们通过///来注释。
例子: 通过cargo new mylib --lib 创建src/lib.rs

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

运行cargo doc会生成这个文档注释的HTML文档。
运行cargo doc --open会构建当前crate文档的HTML并在浏览器中打开。

(3)哪些通常需要注释

  • Panics:这个函数可能会panic!的场景;
  • Errors:如果该函数返回Result类型,此部分会描述会出现哪些错误;
  • Safety:如果这个函数使用unsafe代码,则应该说明。

(4)文档注释作为测试
cargo test也会像文档中的示例代码那样进行测试。
运行方式为:cargo test

src/lib.rs
/// Adds one to the number given
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, mylib::add_one(5)); //运行cargo test,会进行此测试
/// ```
pub fn add_one(x: i32) -> i32 {
    x + 1
}

(5)为crate或者模块整体提供文档的注释://!
例子:src/lib.rs

//! My Crate
//!
//! 'my_crate' is a collection of utilites to make performing certain calculations more convenient
//!
/// Adds one to the number given
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, mylib::add_one(5));
/// ```
pub fn add_one(x: i32) -> i32 {
    x + 1
}

查看效果:

cargo doc --open
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
120
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商