如何从char数组转换[char; N]到字符串切片& str? [英] How do I convert from a char array [char; N] to a string slice &str?

查看:130
本文介绍了如何从char数组转换[char; N]到字符串切片& str?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个固定长度的 char 数组,例如:

Given a fixed-length char array such as:

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

如何获取& str

推荐答案

您不能没有分配,这意味着您最终会得到 String

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

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

问题是Rust中的字符串不是<$ c的 not 集合$ c> char s,它们是UTF-8,这是一种编码,每个字符没有固定大小。

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.

例如,数组在这种情况下,总共需要20个字节才能占用5 x 32位。字符串的数据总共需要5个字节(尽管还有3个指针大小的值,所以在这种情况下,整个 String 会占用更多的内存)。

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).

我们从数组开始并调用 [] :: iter ,其产生的值类型为&字符。然后,我们使用 Iterator :::收集 Iterator< Item =& char> 转换为 String 。这使用迭代器的 size_hint String 中预分配空间,从而减少了额外的分配。

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.

这篇关于如何从char数组转换[char; N]到字符串切片&amp; str?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆