How to put a line into the documentation which is ignored for doc tests?
Asked Answered
S

2

8

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.

Slovene answered 20/2, 2017 at 15:12 Comment(5)
This makes no sense to me. Why do you want to do this?Tolley
I think you have to add ignore after the first three backticks.Sandpiper
@Tolley Because there is no myValue (Could be fixed in this example by adding a let). What I need it for is to use an associated method of a trait on a type which I do not want to show in the documentation because it is not restricted to that one.Slovene
@LukasKalbertodt no cargo just won't run it then except you use something like --allSlovene
Related question: stackoverflow.com/questions/40550665Lukin
R
18

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);
/// ```
Radiolucent answered 20/2, 2017 at 15:21 Comment(5)
The code will still be compiled, so the test will failSlovene
With ignore, or no_run?Radiolucent
with no_run; ignore isn't a perfect solution, because it is for tests which are too expensive but can be run when appropriateSlovene
How about just a comment?Radiolucent
The link is not correct anymore and I didn't find where it's written now.Gemperle
S
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

Swanger answered 20/2, 2017 at 15:21 Comment(2)
Is there also a way to run it? So to run every line except the ignored one?Slovene
You can create several blocks, some ignored, some running normally. They are always displayed, they just don't run etc.Swanger

© 2022 - 2024 — McMap. All rights reserved.