Why len() of &'static is not const?

I can not get the idea how const fn works for &'static str.
str::len defined in const. But I can not write something like this:

const fn f(s:  &'static str) {
   let arr = [0_u8; s.len()];

compiler gives error

attempt to use a non-constant value in a constant

But such code work fine:

const fn f(s: &'static str) -> usize {
const N: usize = f("aaaa");
let arr = [0_u8; N];

So actually length of static str is const,
but why compiler in the first example can not understand that?

This is because s is not a constant in your code. For example, if I call f("a"), then call f("bb") in the same program, the value would not be the same for both calls.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.