Conditional unstable rustc feature?

Viewed 265

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))]
2 Answers

Thanks to the Rust forum I have found out that there are 2 ways to solve the problem:

  • with help of a custom feature declared in cargo file
  • with help of the environment variable RUSTFLAGS

How to enable rustc feature conditionally with a custom feature declared in cargo file?

  1. Declare feature to cargo file. rustc unstable feature will be bound to the one declared in cargo file. For example:
[features]
nightly = []
default = [ "nightly" ]

I chose the name nightly, but it is arbitrary. Feature default describes which features are switched on by default.

  1. Conditionally switch on rustc feature in the root file of your project:
#![ cfg_attr( feature = "nightly", feature( type_name_of_val ) ) ]

feature = "nightly" reffer cargo file feature declared earlier. feature( type_name_of_val ) - declaring of this unstable rustc feature. Note: rustc unstable features should be declared in the root file at the beginning for the whole executable. Otherwise, you will get: crate-level attribute should be in the root module.

  1. Use unstable rustc feature conditionally:
#[ cfg( feature = "nightly" ) ]
println!( "{} is {}", i, std::any::type_name_of_val( &i ) );

#[ cfg( feature = "nightly" ) ] tells compiler to remove the associated line if custom feature nightly is disabled. In our case feature nightly is enabled by default in cargo file default = [ "nightly" ].

How to enable rustc feature conditionally with environment variable RUSTFLAGS?

  1. Conditionally switch on rustc feature in the root file of your project:
#![ cfg_attr( nightly, feature( type_name_of_val ) ) ]

nightly reffer --cfg flag feature( type_name_of_val ) - declaring of this unstable rustc feature. Note: rustc unstable features should be declared in the root file at the beginning for the whole executable. Otherwise, you will get: crate-level attribute should be in the root module.

  1. Use unstable rustc feature conditionally:
#[ cfg( nightly ) ]
println!( "{} is {}", i, std::any::type_name_of_val( &i ) );

#[ cfg( nightly ) ] tells compiler to remove the associated line if rustc does not get cfg nightly. We are going to pass it with the environment variable RUSTFLAGS in the next step.

  1. Run your executable with the environment variable RUSTFLAGS
RUSTFLAGS="--cfg nightly" cargo run

The environment variable RUSTFLAGS="--cfg nightly" tells cargo to pass arguments --cfg nightly to the compiler.

Solutions

Related