How to define a str const for whole string and their parts?
⚓ Rust 📅 2026-04-03 👤 surdeus 👁️ 1I often have a situation as in the example below:
#![feature(const_index)]
const SCRIPT_EXT: &str = ".7b.sh.mk";
const SHELL_SCRIPT: &str = &SCRIPT_EXT[4..6];
fn main() {
println!("myscript.{SHELL_SCRIPT}")
}
Unfortunately, this example isn't compilable, because:
error[E0658]: cannot call conditionally-const operator in constants
--> /media/exhdd/Dev/modu/question/question.rs:4:39
|
4 | const SHELL_SCRIPT: &str = &SCRIPT_EXT[4..6];
| ^^^^^^
|
= note: calls in constants are limited to constant functions, tuple structs and tuple variants
= note: see issue #143874 <https://github.com/rust-lang/rust/issues/143874> for more information
= help: add `#![feature(const_trait_impl)]` to the crate attributes to enable
= note: this compiler was built on 2026-03-20; consider upgrading it if it is out of date
error: aborting due to 1 previous error
It is arguable why slice isn't constant for a constant range? Okay, I use the solution as below to address it:
fn main() {
println!("myscript.{}", &SCRIPT_EXT[4..6])
}
But this solution isn't reliable, because if I changed the source string, I will need to change all addressing the string ranges. How do you address the issue? Introduce range (4..6) type or solve it somehow different?
3 posts - 2 participants
🏷️ Rust_feed