How to create a stack allocated array from &str

let s: &str = "hello world";

i want to make an array of char

There might be a better way to do this, but here is one:

fn main() {
    let s = "Hello World!";
    let mut cs = [' '; 20];
    for (char_ptr, c) in cs.iter_mut().zip(s.chars()) {
        *char_ptr = c;
    println!("{:?}", cs);

has an equivalent:

let bytes = b"hello world";

i want to len of the array to equal to the number of char in s
and calculated by the compiler

That creates a sequence of bytes, although that might be what they wanted.

You can do this if the string is a compile-time constant.

fn main() {
    const s: &str = "Hello World!";
    let mut cs = [' '; s.len()];
    for (char_ptr, c) in cs.iter_mut().zip(s.chars()) {
        *char_ptr = c;
    println!("{:?}", cs);

Although note that this is wrong if the string is not utf-8.

this is only valid for ascii

it returns the number of bytes not the n of chars

Yes, but the number of characters cannot be computed at compile time.

It works for any valid (UTF-8) string, although it returns an array of bytes, as noted above by Alice.

Also note that if you want an array of user-visible characters, that's not going to work with any fixed-size elements, as grapheme clusters are allowed to arbitrarily combine. So iterating over chars probably also doesn't do what you want.

1 Like

In nightly, const fns and libcore have enough features to count the number of chars. :fire:

See playground code

Using the same algorithm as Chars::count.


Try ArrayString:

Also note that the char in Rust is a 4 byte wide type which represents an Unicode scalar value. Is that really what you want?


You can always "trucate" after the loop with
let cs = &mut cs[.. s.chars().count()];

Doing so would be a poor man's / inlined version of ArrayString

answer this

error: byte constant must be ASCII. Use a \xHH escape for a non-ASCII byte
 --> src/
7 |     let s = b"➙";
  |               ^

i want to take a stack allocated str and produce an stack allocated array where each element is a single char.

!!! wait i need a lib just to do this simple thing

It's answered right in the error message. You can use escape sequences to include absolutely any byte in the literal.

the pg example requires s to be const, it won't compile if s is let

i don't want to use escape secq.