add chapter [Docs and Comments]

This commit is contained in:
sunface
2022-03-15 15:46:16 +08:00
parent 346fba581b
commit 843729e128
7 changed files with 403 additions and 2 deletions

2
practices/doc-comments/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target
Cargo.lock

7
practices/doc-comments/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "doc-comments"
version = "0.1.0"

View File

@ -0,0 +1,8 @@
[package]
name = "doc-comments"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@ -0,0 +1,36 @@
//! Do some complicated arithmetic that you can't do by yourself
/// # Panics
///
/// The function panics if the second argument is zero.
///
/// ```rust,should_panic
/// // panics on division by zero
/// doc_comments::compute::div(10, 0);
/// ```
pub fn div(a: i32, b: i32) -> i32 {
if b == 0 {
panic!("Divide-by-zero error");
}
a / b
}
/// ```
/// # fn try_main() -> Result<(), String> {
/// let res = doc_comments::compute::try_div(10, 1)?;
/// # Ok(()) // returning from try_main
/// # }
/// # fn main() {
/// # try_main().unwrap();
/// #
/// # }
/// ```
pub fn try_div(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
Err(String::from("Divide-by-zero"))
} else {
Ok(a / b)
}
}

View File

@ -0,0 +1,54 @@
//! # Doc comments
//!
//! A library for showing how to use doc comments
pub mod compute;
/// Add one to the given value and return a new value
///
/// # Examples
///
/// ```
/// let arg = 5;
/// let answer = doc_comments::add_one(arg);
///
/// assert_eq!(6, answer);
/// ```
pub fn add_one(x: i32) -> i32 {
x + 1
}
/** Add two to the given value and return a new value
# Examples
```
let arg = 5;
let answer = doc_comments::add_two(arg);
assert_eq!(7, answer);
```
*/
pub fn add_two(x: i32) -> i32 {
x + 2
}
/// Add three to the given value and return a [`Option`] type
pub fn add_three(x: i32) -> Option<i32> {
Some(x + 3)
}
mod a {
/// Add four to the given value and return a [`Option`] type
/// [`crate::MySpecialFormatter`]
pub fn add_four(x: i32) -> Option<i32> {
Some(x + 4)
}
}
struct MySpecialFormatter;