2

In rust, I want rustdoc text to link to an enum variant. What is the syntax for that?

Example

Given rust code residing at project file src/common.rs, (this rustdoc code failed to link)

/// your result!
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MyResult<T, E> {
    /// this is good!
    Found(T),
    /// task completed!
    Done,
    /// this is bad!
    Err(E),
}

impl<T, E> MyResult<T, E> {
    /// Returns `true` if the result is [`Found`], [`Done`].
    ///
    /// In other words, this is not an [`Err`](Err)
    ///
    /// [Found]: self::MyResult::Found
    /// [Done]: self::Done
    /// [Err]: crate::common::MyResult::Err
    pub const fn is_ok(&self) -> bool {
        matches!(*self, MyResult::Found(_) | MyResult::Done)
    }
}

fn main() {}

The rust docs are built with command:

cargo doc --locked --release --frozen --no-deps -v

Problem

In the generated rust docs, the various link anchors fail to link to the enum variants within MyResult.

The created doc looks like:

Returns true if the result is [Found], [Done].

In other words, this is not an Err
  • The text [Found], and [Done] fail to link.
  • The text Err links to https://doc.rust-lang.org/beta/core/result/enum.Result.html#variant.Err.
  • I have also tried other variations of linking syntax like
    • /// [Done]: MyResult#variant.Done
    • /// [Done]: self::MyResult#variant.Done


How do I create rust doc intra-doc links to in-module enum variants?

JamesThomasMoon
  • 6,169
  • 7
  • 37
  • 63
  • Similar question [_How to link to other fns/structs/enums/traits in rustdoc?_](https://stackoverflow.com/questions/31582064/how-to-link-to-other-fns-structs-enums-traits-in-rustdoc) – JamesThomasMoon Mar 31 '23 at 21:21

1 Answers1

3

Use syntax form

/// [SomeVariant]: self::MyEnum#variant.SomeVariant

The question's example rustdoc code will have #variant. link anchor:

/// your result!
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MyResult<T, E> {
    /// this is good!
    Found(T),
    /// task completed!
    Done,
    /// this is bad!
    Err(E),
}

impl<T, E> MyResult<T, E> {
    /// Returns `true` if the result is [`Found`], [`Done`].
    ///
    /// In other words, this is not an [`Err`]
    ///
    /// [`Found`]: self::MyResult#variant.Found
    /// [`Done`]: self::MyResult#variant.Done
    /// [`Err`]: self::MyResult#variant.Err
    pub const fn is_ok(&self) -> bool {
        matches!(*self, MyResult::Found(_) | MyResult::Done)
    }
}

fn main() {}

In the rustdoc output, clicking on the text Found then jumps to the definition for the enum variant Found.


Related, linking to methods is similar, use #method. link anchor:

/// [`MyStruct.my_method()`]: self::MyStruct#method.my_method
JamesThomasMoon
  • 6,169
  • 7
  • 37
  • 63