|
| 1 | +# Writing code samples and documentation tests |
| 2 | + |
| 3 | +If your book is about software, a short code sample may communicate the point better than many words of explanation. |
| 4 | +This section describes how to format samples and, perhaps more importantly, how to verify they compile and run |
| 5 | +to ensue they stay aligned with the software APIs they describe. |
| 6 | + |
| 7 | +Code blocks in your book are passed through mdBook and processed by rustdoc. For more details on structuring codeblocks and running doc tests, |
| 8 | +refer to the [rustdoc book](https://doc.rust-lang.org/rustdoc/write-documentation/documentation-tests.html) |
| 9 | + |
| 10 | +### Code blocks for sample code |
| 11 | + |
| 12 | +You include a code sample in your book as a markdown fenced code block specifying `rust`, like so: |
| 13 | + |
| 14 | +`````markdown |
| 15 | +```rust |
| 16 | +let four = 2 + 2; |
| 17 | +assert_eq!(four, 4); |
| 18 | +``` |
| 19 | +````` |
| 20 | + |
| 21 | +This displays as: |
| 22 | + |
| 23 | +```rust |
| 24 | +let four = 2 + 2; |
| 25 | +assert_eq!(four, 4); |
| 26 | +``` |
| 27 | + |
| 28 | +Rustdoc will wrap this sample in a `fn main() {}` so that it can be compiled and even run by `mdbook test`. |
| 29 | + |
| 30 | +#### Disable tests on a code block |
| 31 | + |
| 32 | +rustdoc does not test code blocks which contain the `ignore` attribute: |
| 33 | + |
| 34 | +`````markdown |
| 35 | +```rust,ignore |
| 36 | +fn main() {} |
| 37 | +This would not compile anyway. |
| 38 | +``` |
| 39 | +````` |
| 40 | + |
| 41 | +rustdoc also doesn't test code blocks which specify a language other than Rust: |
| 42 | + |
| 43 | +`````markdown |
| 44 | +```markdown |
| 45 | +**Foo**: _bar_ |
| 46 | +``` |
| 47 | +````` |
| 48 | + |
| 49 | +rustdoc *does* test code blocks which have no language specified: |
| 50 | + |
| 51 | +`````markdown |
| 52 | +``` |
| 53 | +let four = 2 + 2; |
| 54 | +assert_eq!(four, 4); |
| 55 | +``` |
| 56 | +````` |
| 57 | + |
| 58 | +### Hiding source lines within a sample |
| 59 | + |
| 60 | +A longer sample may contain sections of boilerplate code that are not relevant to the current section of your book. |
| 61 | +You can hide source lines within the code block prefixing them with `#_` |
| 62 | +(that is a line starting with `#` followed by a single space), like so: |
| 63 | + |
| 64 | +`````markdown |
| 65 | +```rust |
| 66 | +# use std::fs::File; |
| 67 | +# use std::io::{Write,Result}; |
| 68 | +# fn main() -> Result<()> { |
| 69 | +let mut file = File::create("foo.txt")?; |
| 70 | +file.write_all(b"Hello, world!")?; |
| 71 | +# Ok(()) |
| 72 | +# } |
| 73 | +``` |
| 74 | +````` |
| 75 | + |
| 76 | +This displays as: |
| 77 | + |
| 78 | +```rust |
| 79 | +# use std::fs::File; |
| 80 | +# use std::io::{Write,Result}; |
| 81 | +# fn main() -> Result<()> { |
| 82 | +let mut file = File::create("foo.txt")?; |
| 83 | +file.write_all(b"Hello, world!")?; |
| 84 | +# Ok(()) |
| 85 | +# } |
| 86 | +``` |
| 87 | + |
| 88 | +Note that the code block displays an "show hidden lines" button in the upper right of the code block (when hovered over). |
| 89 | + |
| 90 | +Note, too, that the sample provided its own `fn main(){}`, so the `use` statements could be positioned outside it. |
| 91 | +When rustdoc sees the sample already provides `fn main`, it does *not* do its own wrapping. |
| 92 | + |
| 93 | + |
| 94 | +### Tests using external crates |
| 95 | + |
| 96 | +The previous example shows that you can `use` a crate within your sample. |
| 97 | +But if the crate is an *external* crate, that is, one declared as a dependency in your |
| 98 | +package `Cargo.toml`, rustc (the compiler invoked by rustdoc) needs |
| 99 | +`-L` and `--extern` switches in order to compile it. |
| 100 | +Cargo does this automatically for `cargo build` and `cargo rustdoc` and mdBook can as well. |
| 101 | + |
| 102 | +To allow mdBook to determine the correct external crate information, |
| 103 | +add `package-dir` to your ***book.toml**, as described in [configuration](/format/configuration/general.md#rust-options). |
| 104 | +Note that mdBook runs a `cargo build` for the package to determine correct dependencies. |
| 105 | + |
| 106 | +This example (borrowed from the `serde` crate documentation) compiles and runs in a properly configured book: |
| 107 | + |
| 108 | +```rust |
| 109 | +use serde::{Deserialize, Serialize}; |
| 110 | + |
| 111 | +#[derive(Serialize, Deserialize, Debug)] |
| 112 | +struct Point { |
| 113 | + x: i32, |
| 114 | + y: i32, |
| 115 | +} |
| 116 | + |
| 117 | +fn main() { |
| 118 | + let point = Point { x: 1, y: 2 }; |
| 119 | + |
| 120 | + // Convert the Point to a JSON string. |
| 121 | + let serialized = serde_json::to_string(&point).unwrap(); |
| 122 | + |
| 123 | + // Prints serialized = {"x":1,"y":2} |
| 124 | + println!("serialized = {}", serialized); |
| 125 | + |
| 126 | + // Convert the JSON string back to a Point. |
| 127 | + let deserialized: Point = serde_json::from_str(&serialized).unwrap(); |
| 128 | + |
| 129 | + // Prints deserialized = Point { x: 1, y: 2 } |
| 130 | + println!("deserialized = {:?}", deserialized); |
| 131 | +} |
| 132 | +``` |
0 commit comments