How do I convert from a char array [char; N] to a string slice &str?

后端 未结 2 1472
失恋的感觉
失恋的感觉 2021-01-24 06:08

Given a fixed-length char array such as:

let s: [char; 5] = [\'h\', \'e\', \'l\', \'l\', \'o\'];

How do I obtain a &str<

相关标签:
2条回答
  • 2021-01-24 06:41

    I will give you a very simple functional solution but it's not the best one. You can learn some basics:

    let s: [char; 5] = ['h', 'e', 'l', 'l', 'o'];
    let mut str = String::from("");
    for x in &s {
        str.push(*x);
    }
    println!("{}", str);
    

    Before the variable names you can put an underscore if you want to keep the signature, but in this simple example it is not necessary. The program starts by creating an empty mutable String so you can add elements (chars) to the String. Then we make a for loop over the s array by taking its reference. We add each element to the initial string. At the end you can return your string or just print it.

    0 讨论(0)
  • 2021-01-24 06:48

    You can't without some allocation, which means you will end up with a String.

    let s2: String = s.iter().collect();
    

    The problem is that strings in Rust are not collections of chars, they are UTF-8, which is an encoding without a fixed size per character.

    For example, the array in this case would take 5 x 32-bits for a total of 20 bytes. The data of the string would take 5 bytes total (although there's also 3 pointer-sized values, so the overall String takes more memory in this case).


    We start with the array and call []::iter, which yields values of type &char. We then use Iterator::collect to convert the Iterator<Item = &char> into a String. This uses the iterator's size_hint to pre-allocate space in the String, reducing the need for extra allocations.

    0 讨论(0)
提交回复
热议问题