Any way to create an item that is built only for the documentation?

I haven't seen any way to create a module that is only built for the documentation. I'd love to create an examples module that is only built during documentation or testing.

I think you can use #[cfg(rustdoc)]. Rust 1.40 also now has #[cfg(doctest)].

Are these documented anywhere?

It looks like cfg(rustdoc) is still unstable. Here is cfg(doctest), and it was mentioned in the 1.40 release notes.

Just to clarify here, cfg(doctest) means that the code is only used when generating doctests, not when creating documentation. So it seems there is no stable way to generate an item only for documentation.

Perhaps you could put that documentation item behind a compile flag, and use the compile flag when generating documentation. It's not quite as nice as an attribute, but you can write a simple build script that passes the real work down to Cargo to lock down the fact that docs need to be built using the compile flag.

And if your docs are hosted on docs.rs, you can add custom metadata to Cargo.toml to tell docs.rs to pass the correct compiler flag. For example:

[package.metadata.docs.rs] 
rustdoc-args = [ "--cfg", "doc" ]
2 Likes