Function list_enabled_as_string

Source
pub fn list_enabled_as_string(const_name: &str) -> String
Expand description

Generates a constant declaration containing enabled Cargo features.

It’s a wrapper around list_enabled that provides a String that should be usable as is in an output file of the build script. This function should only be called in build scripts or code executed during a Cargo build process, as the required CARGO_FEATURE_* environment variables will be missing otherwise.

See also list_enabled_as_string_with_path.

§Panics

Panics if the Cargo.toml file cannot be read.

§Arguments

  • const_name - Name of the constant to generate.

§Returns

A String containing the code for the constant declaration, like:

String::from(r#"pub const CONST_NAME: &[&str] = &[
"feature1",
"feature2",
];"#);

§Examples

// in build.rs
let out_dir = std::env::var("OUT_DIR").unwrap();
let file_path = format!("{out_dir}/build_info.rs");
let features = list_features::list_enabled_as_string("ENABLED_FEATURES");
std::fs::write(file_path, features).unwrap();

// in main.rs
include!(concat!(env!("OUT_DIR"), "/build_info.rs"));
for feature in ENABLED_FEATURES {
  println!(output, " {feature}");
}