Conditional experimental rustc feature?

I need to have removed line switching on the experimental rustc feature if the current rustc is stable. Is that possible something like that?

#![cfg_attr(rustversion::nightly, feature(type_name_of_val))]

No. To do that, you need to set up a feature or a --cfg flag for your crate that the user enables when they use nightly.

3 Likes

Hi @alice. Thanks for response. How to do it?

To do it with a feature flag, check out these links from serde:

  1. Cargo.toml
  2. Enable unstable feature in lib.rs
  3. Use unstable feature elsewhere

To do it with a --cfg flag, check out these links from Tokio:

  1. It is not necessary to list the --cfg flag in Cargo.toml.
  2. Enable unstable feature in lib.rs
  3. Disabling code without the flag
  4. Set attribute when flag is set
  5. Enable flag when building documentation on docs.rs

The example from Tokio is for a flag called docsrs. Tokio uses this flag to enable certain nightly-only features when building documentation, but the same concept can be used to enable unstable features when building normally.

To enable the unstable feature of serde, you do this in your Cargo.toml:

serde = { version = "1", features = ["unstable"] }

To enable the docsrs flag of Tokio, you do this when calling cargo build:

RUSTFLAGS="--cfg docsrs" cargo build

A --cfg flag cannot be enabled by changing your Cargo.toml file. Rather, it must be set by the person calling the build command.

3 Likes

That is useful! Thank you Alice. I summarized all that here.

Solutions

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.