Add unstable feature only if compiled on nightly

I’m trying to make a crate which can be compiled on stable, but which will include a benchmark, available if the crate is compiled on nightly. I’ve tried to add #[cfg(nightly)] on the testing module, but it forces it to stop compiling at all - seems that this is the wrong way? - and also I had to specify the #![feature(test)] at the crate root, while, again, wasn’t able to restrict it to the “nightly only”. Is it ever possible?

There’s no built-in #[cfg(nightly)], but you can achieve this in a build script if you detect the rustc version yourself and output cargo:rustc-cfg=nightly. The new select-rustc crate offers a macro way to do this with #[rustc::nightly]. Some crates instead use an explicit Cargo.toml feature, which you would then check with #[cfg(feature = "nightly")].

1 Like

I see. Is it possible, then, to ever conditionally add unstable features (#![feature(test)], in particular)? Just adding #![cfg(feature = "...")] on the top of the crate seems to remove the source code altogether when the feature is not specified.

You can use #![cfg_attr(feature = "...", feature(test))]

2 Likes