Why there is no macro to work with named string constants?

I wanted to write a simple code using constants:

const A: &str = "1";

fn main() {
println!("{}", concat!(env!("HOME"), "2"));
println!("{}", concat!(A, "2"));
}

The code does not compile and:

error: expected a literal
 --> src/main.rs:6:24
  |
6 | println!("{}", concat!(A, "2"));
  |                        ^
  |
  = note: only literals (like `"foo"`, `42` and `3.14`) can be passed to `concat!()`

error: aborting due to previous error

error: Could not compile `playground`.

I understand that macro_rules of concat! expect there to have literals only. But from Rust's point of view, A should also be treated as a compile-time constant (like a constexpr in C++):

constants are inlined wherever they're used, making using them identical to simply replacing the name of the const with its value.

I've also tried to use a const fn but the result is still the same.
Shouldn't Rust handle this case inside concat! macro or at least have another macro which would make this actually possible?

Or still, it is "identical" only for the user, but not for the compiler? Anyway, from a user perspective, this should be treated the same. Otherwise, we simply don't have any way to have a named constant in the code.

Macro expansion is one of the first things that happens in Rust. Unfortunately this means fetching the values of const can't happen during macro expansion in the current architecture.

The const-concat crate has a workaround for this, but it's nightly-only for now.

const ONE: &str = "1";
const TWELVE: &str = const_concat!(ONE, "2");

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.