Why can't I call .chars().count() on a const &str?

fn main() {
    const s: &str = "⊗ symbol";
    const n: usize =  s.chars().count();

    println!("{}", n);
}

why i can't compile this. even though s is const. so the n of char is const and so count is const and know at compile time.

the chars and count methods are not const fns. See previous thread where there was some code to count chars (in a low level way) for consts.

The number of const fns in the standard library is gradually being expanded.

1 Like

const doesn't mean immutable, it means compile time, similar to C++'s constexpr. Normal let bindings are immutable by default, so you can just use those.

1 Like

A const fn can't yet have any loops or control flow. This is being worked on but for now anything that requires iteration can't be const.

For future reference: that is this thread from 4 days ago with about the same question.

1 Like