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.