Reputation: 9965
Is there a way to include something into documentation scope without including it into the code scope? My Rustdoc links to a Trait that's not in the code scope. If I add use std::ops::Add
at the top, I get unused import
warning from cargo build
. If I don't add it, I get unresolved link
warning from cargo doc
.
In theory, cargo build
should not warn me because rustdoc is in the same scope as the main code, but it does.
/// [Add]
pub fn foo() {}
Upvotes: 2
Views: 1018
Reputation: 115
While #[cfg(doc)]
as @ChayimFriedman suggested works fine, I couldn't find a way to highlight unused imports for docs, which is e.g. needed when a documentation is updated later and the link is removed.
// doesn't warn about unused import, even if there is no link anymore
#[cfg(doc)]
use std::ops::Add;
/// documentation without link
pub fn foo() {}
Therefore, \\\ [Add](std::ops::Add)
, as suggested by @SilvioMayolo, seems to be more suitable long-term, even if it means more typing.
If you add a link with qualified path to your documentation, you don't get any warnings:
// generates no warnings
/// [Add](std::ops::Add)
pub fn foo() {}
If you forgot to add the path for a docs link where the import is missing (or if you later refactor your code and remove an import needed for a link), the rustdoc::broken_intra_doc_links
lint has you covered and will warn about an unresolved link.
// warns about unresolved link
/// [Add]
pub fn foo() {}
If you later add an import that is already used in a link, the rustdoc::redundant_explicit_links
lint has you covered and will warn you about a redundant explicit link target.
// warns about redundant explicit link target
use std::ops::Add;
/// [Add](std::ops::Add)
pub fn foo() {}
While both lints are warn-by-default, you can also make this explicit by adding the lints to your main.rs and/or lib.rs.
#![warn(rustdoc::broken_intra_doc_links)]
#![warn(rustdoc::redundant_explicit_links)]
You could also use deny()
or forbid()
instead of warn()
to prevent your documentation from being created while there are linking errors.
Upvotes: 2
Reputation: 71025
You can use #[cfg(doc)]
:
#[cfg(doc)]
use std::ops::Add;
/// [Add]
pub fn foo() {}
Or just use the full name, as suggested by @SilvioMayolo.
Upvotes: 3
Reputation: 70287
You can fully qualify the link.
/// [Add](std::ops::Add)
Note that the syntax you've been using is shorthand for
/// [Add](Add)
and the thing in parentheses at the end can be any valid qualified name, including fully qualified ones starting at std
or the name of some other crate.
Upvotes: 4