kingledion
kingledion

Reputation: 2510

Can you use a const value in docs in Rust?

Can you use a const's value in documentation in rust? Something like string interpolation to insert a value:

const EXPIRATION_TIME_IN_MINUTES: i64 = 60*24;

/// A struct that does something
/// Whatever this struct does, it expires in ${EXPIRATION_TIME_IN_MINUTES} minutes. 
struct SomeStruct {
   ...
}

The proposed use case is exactly this, documenting what the default setting for expiration for a function.

Upvotes: 4

Views: 1116

Answers (2)

Peter Hall
Peter Hall

Reputation: 58805

Typical documentation that references a constant would do it by adding documentation in two places and linking them together:

/// The expiration time used for instances of `SomeStruct`, in minutes.
const EXPIRATION_TIME_IN_MINUTES: i64 = 60 * 24;

/// A struct that does something. The expiration associated with this struct 
/// is given by the constant [`EXPIRATION_TIME_IN_MINUTES`].
struct SomeStruct {
   ...
}

Even though the value of the constant will not appear inline, using [``] will create a hyperlink to the docs for the constant so a user can see the value there.

Upvotes: 5

Chayim Friedman
Chayim Friedman

Reputation: 71380

No. I think rustdoc does not even perform const evaluation.

For documenting the default value, if it is really long, you can create a macro that expands to it and use it in documentation comments. It works like:

macro_rules! default_value {
    () => { 1440 };
}

const EXPIRATION_TIME_IN_MINUTES: i64 = default_value!();

/// A struct that does something
#[doc = concat!(" Whatever this struct does, it expires in ", default_value!(), " minutes.")]
struct SomeStruct {
}

The /// comment expands to #[doc = "..."] (//! comments expand to #![doc = "..."]). However, you cannot place expressions there, only literals, so it may not help you.

Upvotes: 3

Related Questions