]> git.lizzy.rs Git - rust.git/blob - src/doc/rustdoc/src/scraped-examples.md
Rollup merge of #106811 - khuey:dwp_extension, r=davidtwco
[rust.git] / src / doc / rustdoc / src / scraped-examples.md
1 # Scraped examples
2
3 Rustdoc has an unstable feature where it can automatically scrape examples of items being documented from the `examples/` directory of a Cargo workspace. These examples will be included within the generated documentation for that item. For example, if your library contains a public function:
4
5 ```rust,ignore (needs-other-file)
6 // a_crate/src/lib.rs
7 pub fn a_func() {}
8 ```
9
10 And you have an example calling this function:
11
12 ```rust,ignore (needs-other-file)
13 // a_crate/examples/ex.rs
14 fn main() {
15   a_crate::a_func();
16 }
17 ```
18
19 Then this code snippet will be included in the documentation for `a_func`. This documentation is inserted by Rustdoc and cannot be manually edited by the crate author.
20
21
22 ## How to use this feature
23
24 This feature is unstable, so you can enable it by calling Rustdoc with the unstable `rustdoc-scrape-examples` flag:
25
26 ```bash
27 cargo doc -Zunstable-options -Zrustdoc-scrape-examples=examples
28 ```
29
30 To enable this feature on [docs.rs](https://docs.rs), add this to your Cargo.toml:
31
32 ```toml
33 [package.metadata.docs.rs]
34 cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples=examples"]
35 ```
36
37
38 ## How it works
39
40 When you run `cargo doc`, Rustdoc will analyze all the crates that match Cargo's `--examples` filter for instances of items being documented. Then Rustdoc will include the source code of these instances in the generated documentation.
41
42 Rustdoc has a few techniques to ensure these examples don't overwhelm documentation readers, and that it doesn't blow up the page size:
43
44 1. For a given item, a maximum of 5 examples are included in the page. The remaining examples are just links to source code.
45 2. Only one example is shown by default, and the remaining examples are hidden behind a toggle.
46 3. For a given file that contains examples, only the item containing the examples will be included in the generated documentation.
47
48 For a given item, Rustdoc sorts its examples based on the size of the example — smaller ones are shown first.
49
50
51 ## FAQ
52
53 ### My example is not showing up in the documentation
54
55 This feature uses Cargo's convention for finding examples. You should ensure that `cargo check --examples` includes your example file.