Files
rust-by-practice/comments-docs.html
sunface 987c59ed75 deploy
2025-04-25 12:48:03 +08:00

489 lines
21 KiB
HTML

<!DOCTYPE HTML>
<html lang="en" class="light sidebar-visible" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Comments and Docs - Rust By Practice</title>
<!-- Custom HTML head -->
<meta name="description" content="Learn Rust with Example, Exercise and real Practice, written with ❤️ by https://course.rs team">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="favicon.svg">
<link rel="shortcut icon" href="favicon.png">
<link rel="stylesheet" href="css/variables.css">
<link rel="stylesheet" href="css/general.css">
<link rel="stylesheet" href="css/chrome.css">
<link rel="stylesheet" href="css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" id="highlight-css" href="highlight.css">
<link rel="stylesheet" id="tomorrow-night-css" href="tomorrow-night.css">
<link rel="stylesheet" id="ayu-highlight-css" href="ayu-highlight.css">
<!-- Custom theme stylesheets -->
<link rel="stylesheet" href="theme/style1.css">
<!-- Provide site root and default themes to javascript -->
<script>
const path_to_root = "";
const default_light_theme = "light";
const default_dark_theme = "navy";
</script>
<!-- Start loading toc.js asap -->
<script src="toc.js"></script>
</head>
<body>
<div id="body-container">
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
let theme = localStorage.getItem('mdbook-theme');
let sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
let theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
const html = document.documentElement;
html.classList.remove('light')
html.classList.add(theme);
html.classList.add("js");
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
let sidebar = null;
const sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<!-- populated by js -->
<mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox>
<noscript>
<iframe class="sidebar-iframe-outer" src="toc.html"></iframe>
</noscript>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="default_theme">Auto</button></li>
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">Rust By Practice</h1>
<div class="right-buttons">
<a href="print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://github.com/sunface/rust-by-practice" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
<a href="https://github.com/sunface/rust-by-practice/edit/master/en/src/comments-docs.md" title="Suggest an edit" aria-label="Suggest an edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h1 id="comments-and-docs"><a class="header" href="#comments-and-docs">Comments and Docs</a></h1>
<p>Every program requires comments:</p>
<h2 id="comments"><a class="header" href="#comments">Comments</a></h2>
<ul>
<li>Regular comments which are ignored by the compiler:
<ul>
<li><code>// Line comment, which goes to the end of the line</code></li>
<li><code>/* Block comment, which goes to the end of the closing delimiter */</code></li>
</ul>
</li>
</ul>
<h3 id="examples"><a class="header" href="#examples">Examples</a></h3>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
// This is an example of a line comment
// There are two slashes at the beginning of the line
// And nothing written inside these will be read by the compiler
// println!("Hello, world!");
// Run it. See? Now try deleting the two slashes, and run it again.
/*
* This is another type of comment, a block comment. In general,
* line comments are the recommended comment style. But
* block comments are extremely useful for temporarily disabling
* chunks of code. /* Block comments can be /* nested, */ */
* so it takes only a few keystrokes to comment out everything
* in this main() function. /*/*/* Try it yourself! */*/*/
*/
/*
Note: The previous column of `*` was entirely for style. There's
no actual need for it.
*/
}</code></pre></pre>
<h3 id="exercises"><a class="header" href="#exercises">Exercises</a></h3>
<ol>
<li>🌟🌟</li>
</ol>
<pre><pre class="playground"><code class="language-rust editable edition2021">
/* Make it work, only using comments! */
fn main() {
todo!();
unimplemented!();
assert_eq!(6, 5 + 3 + 2 + 1 )
}</code></pre></pre>
<h2 id="doc-comments"><a class="header" href="#doc-comments">Doc Comments</a></h2>
<ul>
<li>Doc comments which are parsed into HTML and supported <code>Markdown</code>
<ul>
<li><code>/// Generate library docs for the following item</code></li>
<li><code>//! Generate library docs for the eclosing item</code></li>
</ul>
</li>
</ul>
<p>Before starting, we need to create a new package for practice: <code>cargo new --lib doc-comments</code>.</p>
<h3 id="line-doc-comments-"><a class="header" href="#line-doc-comments-">Line doc comments <code>///</code></a></h3>
<p>Add docs for function <code>add_one</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// in lib.rs
/// Add one to the given value and return the value
///
/// # Examples
///
/// ```
/// let arg = 5;
/// let answer = my_crate::add_one(arg);
///
/// assert_eq!(6, answer);
/// ```
pub fn add_one(x: i32) -&gt; i32 {
x + 1
}
<span class="boring">}</span></code></pre></pre>
<h3 id="cargo-doc"><a class="header" href="#cargo-doc">Cargo doc</a></h3>
<p>We can use <code>cargo doc --open</code> to generate html files and open them in the browser.</p>
<h3 id="block-doc-comments---"><a class="header" href="#block-doc-comments---">Block doc comments <code>/** ... */</code></a></h3>
<p>Add docs for function <code>add_two</code>:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/** Add two to the given value and return a new value
<span class="boring">Examples
</span>
let arg = 5;
let answer = my_crate::add_two(arg);
assert_eq!(7, answer);
*/
pub fn add_two(x: i32) -&gt; i32 {
x + 2
}
<span class="boring">}</span></code></pre></pre>
<h3 id="doc-comments-for-crate-and-module"><a class="header" href="#doc-comments-for-crate-and-module">Doc comments for crate and module</a></h3>
<p>We can also add doc comments for our crates and modules.</p>
<p>Firstly, let's add some doc comments for our library crate:</p>
<blockquote>
<p>Note: We must place crates and module comments at the top of crate root or module file.</p>
</blockquote>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>//! # Doc comments
//!
//! A library for showing how to use doc comments
// in lib.rs
pub mod compute;
<span class="boring">}</span></code></pre></pre>
<p>You can also use block comments to achieve this:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/*! # Doc comments
A library for showing how to use doc comments */
<span class="boring">}</span></code></pre></pre>
<p>Next, create a new module file <code>src/compute.rs</code>, and add following comments to it:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>//! //! Do some complicated arithmetic that you can't do by yourself
// in compute.rs
<span class="boring">}</span></code></pre></pre>
<p>Then run <code>cargo doc --open</code> and see the results.</p>
<h3 id="doc-tests"><a class="header" href="#doc-tests">Doc tests</a></h3>
<p>The doc comments of <code>add_one</code> and <code>add_two</code> contain two example code blocks.</p>
<p>The examples can not only demonstrate how to use your library, but also running as test with <code>cargo test</code> command.</p>
<ol start="2">
<li>🌟🌟 But there are errors in the two examples, please fix them, and running with <code>cargo test</code> to get following result:</li>
</ol>
<pre><code class="language-shell">running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests doc-comments
running 2 tests
test src/lib.rs - add_one (line 11) ... ok
test src/lib.rs - add_two (line 26) ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.55s
</code></pre>
<ol start="3">
<li>🌟🌟 Sometimes we expect an example to be panic, add following code to <code>src/compute.rs</code> and make the <code>cargo test</code> passed.</li>
</ol>
<blockquote>
<p>You can only modify the comments, DON'T modify <code>fn div</code></p>
</blockquote>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// in src/compute.rs
/// # 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) -&gt; i32 {
if b == 0 {
panic!("Divide-by-zero error");
}
a / b
}
<span class="boring">}</span></code></pre></pre>
<ol start="4">
<li>🌟🌟 Sometimes we want to hide the doc comments, but keep the doc tests.</li>
</ol>
<p>Add following code to <code>src/compute.rs</code> ,</p>
<pre><pre class="playground"><code class="language-rust edition2021">// in src/compute.rs
/// ```
/// # fn try_main() -&gt; Result&lt;(), String&gt; {
/// # let res = doc_comments::compute::try_div(10, 0)?;
/// # Ok(()) // returning from try_main
/// # }
/// # fn main() {
/// # try_main().unwrap();
/// #
/// # }
/// ```
pub fn try_div(a: i32, b: i32) -&gt; Result&lt;i32, String&gt; {
if b == 0 {
Err(String::from("Divide-by-zero"))
} else {
Ok(a / b)
}
}</code></pre></pre>
<p>and modify this code to achieve two goals:</p>
<ul>
<li>The doc comments must not be presented in html files generated by <code>cargo doc --open</code></li>
<li>run the tests, you should see results as below:</li>
</ul>
<pre><code class="language-shell">running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests doc-comments
running 4 tests
test src/compute.rs - compute::div (line 7) ... ok
test src/lib.rs - add_two (line 27) ... ok
test src/lib.rs - add_one (line 11) ... ok
test src/compute.rs - compute::try_div (line 20) ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.51s
</code></pre>
<h3 id="code-navigation"><a class="header" href="#code-navigation">Code navigation</a></h3>
<p>Rust provide a very powerful feature for us, that is code navigation in doc comments.</p>
<p>Add following code to <code>src/lib.rs</code>:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// in lib.rs
/// Add three to the given value and return a [`Option`] type
pub fn add_three(x: i32) -&gt; Option&lt;i32&gt; {
Some(x + 3)
}
<span class="boring">}</span></code></pre></pre>
<p>Besides jump into the standard library, you can also jump to another module in the package.</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// in lib.rs
mod a {
/// Add four to the given value and return a [`Option`] type
/// [`crate::MySpecialFormatter`]
pub fn add_four(x: i32) -&gt; Option&lt;i32&gt; {
Some(x + 4)
}
}
struct MySpecialFormatter;
<span class="boring">}</span></code></pre></pre>
<h3 id="doc-attributes"><a class="header" href="#doc-attributes">Doc attributes</a></h3>
<p>Below are a few examples of the most common <code>#[doc]</code> attributes used with <code>rustdoc</code>.</p>
<h3 id="inline"><a class="header" href="#inline"><code>inline</code></a></h3>
<p>Used to inline docs, instead of linking out to separate page.</p>
<pre><code class="language-rust ignore">#[doc(inline)]
pub use bar::Bar;
/// bar docs
mod bar {
/// the docs for Bar
pub struct Bar;
}</code></pre>
<h3 id="no_inline"><a class="header" href="#no_inline"><code>no_inline</code></a></h3>
<p>Used to prevent linking out to separate page or anywhere.</p>
<pre><code class="language-rust ignore">// Example from libcore/prelude
#[doc(no_inline)]
pub use crate::mem::drop;</code></pre>
<h3 id="hidden"><a class="header" href="#hidden"><code>hidden</code></a></h3>
<p>Using this tells <code>rustdoc</code> not to include this in documentation:</p>
<pre><code class="language-rust editable ignore">// Example from the futures-rs library
#[doc(hidden)]
pub use self::async_await::*;</code></pre>
<p>For documentation, <code>rustdoc</code> is widely used by the community. It's what is used to generate the <a href="https://doc.rust-lang.org/std/">std library docs</a>.</p>
<h3 id="full-code"><a class="header" href="#full-code">Full Code</a></h3>
<p>The full code of package <code>doc-comments</code> is <a href="https://github.com/sunface/rust-by-practice/tree/master/practices/doc-comments">here</a>.</p>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="crate-module/use-pub.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="formatted-output/intro.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="crate-module/use-pub.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="formatted-output/intro.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script>
window.playground_copyable = true;
</script>
<script src="ace.js"></script>
<script src="editor.js"></script>
<script src="mode-rust.js"></script>
<script src="theme-dawn.js"></script>
<script src="theme-tomorrow_night.js"></script>
<script src="elasticlunr.min.js"></script>
<script src="mark.min.js"></script>
<script src="searcher.js"></script>
<script src="clipboard.min.js"></script>
<script src="highlight.js"></script>
<script src="book.js"></script>
<!-- Custom JS scripts -->
<script src="assets/custom3.js"></script>
<script src="assets/lang1.js"></script>
</div>
</body>
</html>