Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

char

rust

Given a fixed-length char array such as:

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

How do I obtain a &str?

like image 327
Rufflewind Avatar asked Jul 13 '16 18:07

Rufflewind


People also ask

How do you convert this char array to string?

char[] arr = { 'p', 'q', 'r', 's' }; The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);


1 Answers

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.

like image 106
Shepmaster Avatar answered Oct 19 '22 05:10

Shepmaster