Why can Rust not use const as literals?

Viewed 523

Consider this code:

const VERSION: &'static str = env!("CARGO_PKG_VERSION");

fn main() {
    // OK
    println!("{}", "0.1.0");
    // OK
    println!("{}", env!("CARGO_PKG_VERSION"));
    // OK
    println!("{}", VERSION);
    // OK
    println!("0.1.0");
    // OK
    println!(env!("CARGO_PKG_VERSION"));
    // error: format argument must be a string literal
    println!(VERSION);
}

The Rust doc of const states that const creates a compile-time constant, and in env! states that the env! macro creates a compile-time known &'static str value.

I'm curious, given that all these three values are known at compile-time with a fixed size, why can't they be used interchangeably? Why aren't they semantically equivalent?

1 Answers

This is done in an intrinsic (compiler code). So plausibly an implementation restriction or oversight.

If you open an issue in the Rust repository perhaps they will fix it.

Related