6

How can I write a line into the documenation code but let the compiler ignore it?

I want to write

/// # Examples
///
/// To clone something, do
///
/// ```
/// IGNORE_FOR_COMPILATION_BUT_SHOW: let cloned = myValue.clone();
/// # let cloned = 5.clone();
/// ```

And I want to get:

Examples

To clone somthing, do

let cloned = myValue.clone();

But the compiler should still compile the example (cloning the 5).

EDIT: I also want cargo to run the example, but leave out one line.

torkleyy
  • 1,137
  • 9
  • 26

2 Answers2

14

The documentation says you can do this:

/// ```rust,ignore
/// highlighted as rust code but ignored by rustdoc
/// ```

There is also rust,no_run which compiles but doesn't run the example code.

Alternatively, you could use the same solution as you would in ordinary code: comment it out.

/// ```rust
/// let x=5;
/// // x = 6;  // won't be run
/// assert_eq!(x, 5);
/// ```
Ross MacArthur
  • 4,735
  • 1
  • 24
  • 36
Chris Emerson
  • 13,041
  • 3
  • 44
  • 66
6

If you want to ignore a part of Rust code in doctests, you might want to read the section on running documentation tests. Basically extract that code into a different block and set that block to rust,ignore.

This will ignore IGNORE_FOR_COMPILATION_BUT_SHOW completely, but the rest will run:

///```rust,ignore
///IGNORE_FOR_COMPILATION_BUT_SHOW: let cloned = myValue.clone(); 
///```

///```rust
/// # let cloned = 5.clone();
/// ```

If you want rustdoc to compile your doc tests, but not run it, you can use rust,no_run

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Daniel Fath
  • 16,453
  • 7
  • 47
  • 82