0
点赞
收藏
分享

微信扫一扫

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


视频地址

头条地址:https://www.ixigua.com/i6775861706447913485
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


举报

相关推荐

0 条评论