How to define a str const for whole string and their parts?

I 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?

You probably want to use static instead of const, since const drops new copies all over the place. And although you can't index in a const context, split_at can be used instead. So something ugly-but-workable could look like:

1 Like

Thanks, and static is sufficient only for ranges.