How can I nest code blocks in docstrings?

I would like to nest code blocks in a docstring:

/// You can use the following template to document your function:
///
/// ```text
/// This function does things.
/// ```text
/// inner block of text
/// ```
/// It is a cool function.
/// ```
///
/// When using the template above, be sure to yada yada…

(How) can I achieve this?

What I've Tried

  • The r#"foo"# syntax. It does not seem to exist for triple-backticks.
  • Escaping a backtick of the inner triple-backtick pair. This “works” in that it doesn't break rustdoc, but renders a backslash, which I'd like to avoid.
  • #[doc = /* … */] syntax. I can't get it to work.

as far as I know, markdown doesn't support this.

Try using a different code fence for either one of the two blocks:

/// You can use the following template to document your function:
///
/// ~~~text
/// This function does things.
/// ```text
/// inner block of text
/// ```
/// It is a cool function.
/// ~~~
///
/// When using the template above, be sure to yada yada…

Renders like this:

3 Likes

The other way to do this in markdown generally (I didn't test rustdoc) is to use more backticks at the outer levels.

Like so:
````
This function does things.
```rust
fn example() { ... }
```
````
1 Like

Can confirm this works in rustdoc. It's what I ended up doing after learning the term “code fence” and consequently more about them from @jofas. :bow:

1 Like