rust

Check whether compiler is nightly at compile time


That is it: how do I know whether the project is building by nightly or stable compiler? Something like this:

#[cfg(nightly_build)]
use std::ptr::Shared; // on nightly use system's version

#[cfg(not(nightly_build))]
use myshared::Shared; // on stable use my unoptimized Shared

Solution

  • You can do it with the rustc_version crate and a build.rs script:

    extern crate rustc_version;
    use rustc_version::{version_meta, Channel};
    
    fn main() {
        // Set cfg flags depending on release channel
        match version_meta().unwrap().channel {
            Channel::Stable => {
                println!("cargo:rustc-cfg=RUSTC_IS_STABLE");
            }
            Channel::Beta => {
                println!("cargo:rustc-cfg=RUSTC_IS_BETA");
            }
            Channel::Nightly => {
                println!("cargo:rustc-cfg=RUSTC_IS_NIGHTLY");
            }
            Channel::Dev => {
                println!("cargo:rustc-cfg=RUSTC_IS_DEV");
            }
        }
    }
    

    Then check it with #[cfg(feature = "RUSTC_IS_STABLE")], etc in the Rust code.